Scala将字符串列表转换为多个变量

时间:2015-03-31 09:51:50

标签: string scala

我试图将字符串列表转换为多个变量,这样我就可以将属性设置为列表内容。

mycode的:

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 个答案:

答案 0 :(得分:8)

您可以使用模式匹配:

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

在元组的情况下,只需在val声明周围添加大括号,如下所示:

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

答案 1 :(得分:-1)

你不能在香草Scala中做到这一点。但是,shapeless库提供了一些通常用于处理元组的工具。以下作品:

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

请注意,attributes实际上是Option[Attributes],因为如果类型或长度错误,List -> HList转换可能会失败(不是在这种特殊情况下,而是一般情况下)。

相关问题