2

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
}

2 Answers 2

8

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
  }
Sign up to request clarification or add additional context in comments.

Comments

-1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.