在 Scala 中将字符串列表转换或转换为用户定义的对象
Cast or convert a list of String to a user defined object in Scala
假设我有一个字符串列表:
val myList: List[String] = List("A", "B", "C")
有没有办法 convert/cast 这个列表到用户定义的对象而不用硬编码,类似于:
case class MyClass(name1: String, name2: String, name3: String)
val result: MyClass = myList.asInstanceOf[MyClass]
val result: MyClass = myList match {
case name1 :: name2 :: name3 :: Nil => MyClass(name1, name2, name3)
case _ => MyClass("", "", "") // default case, if list has less than 3 strings
}
假设我有一个字符串列表:
val myList: List[String] = List("A", "B", "C")
有没有办法 convert/cast 这个列表到用户定义的对象而不用硬编码,类似于:
case class MyClass(name1: String, name2: String, name3: String)
val result: MyClass = myList.asInstanceOf[MyClass]
val result: MyClass = myList match {
case name1 :: name2 :: name3 :: Nil => MyClass(name1, name2, name3)
case _ => MyClass("", "", "") // default case, if list has less than 3 strings
}