Eddie
Eddie

Reputation: 95

Scala convert list of Strings to multiple variables

I'm trying to convert a list of strings to multiple variables so that I can assign attributes to the content of list.

My code:

val list = List("a", "b", "c", "d", "e", "f")
val attributes = Attributes(#SomeAwesomeScalaCode#) 

case class Attributes(input:(String, String, String, String, String, String)) {
val a, b, c, d, e, f = input
}

Upvotes: 2

Views: 603

Answers (2)

Vladimir Matveev
Vladimir Matveev

Reputation: 127791

You can't do this in vanilla Scala. However, the shapeless library provide some tools to work with tuples generically. The following works:

import shapeless._
import shapeless.syntax.std.traversable._

case class Attributes(input: (String, String, String, String, String, String)) {
  val a, b, c, d, e, f = input
}

object Main extends App {
  val list = List("a", "b", "c", "d", "e", "f")

  val attributes = list.toHList[String :: String :: String :: String :: String :: String :: HNil].map(hl => Attributes(hl.tupled))

  println(attributes)
}

Note that attributes is actually Option[Attributes] because List -> HList conversion may fail if types or length are wrong (not in this particular case, but in general).

Upvotes: -1

Gregor Raýman
Gregor Raýman

Reputation: 3081

You could use the pattern matching:

  val List(a, b, c, d) = List("1", "2", "3", "4")

in the case of tuple, just add the braces around the val declaration like this:

  case class Attributes(input:(String, String, String, String, String, String)) {
     val (a, b, c, d, e, f) = input
  }

Upvotes: 8

Related Questions