issykazz issykazz - 1 year ago 129
Scala Question

Cast or convert a list of String to a user defined object in Scala

Let say I Have a list of strings:
val myList: List[Sting] = List("A", "B", "C")

Is there a way to convert/cast this list to a user defined Object without hardcoding, something on the lines of :

case class MyClass(name1: String, name2: String, name3: String)
val result: MyClass = myList.asInstanceOf[MyClass]

Answer Source
val result: MyClass = myList match {
  case name1 :: name2 :: name3 :: _ => MyClass(name1, name2, name3)
  case _ => MyClass("", "", "") // default case, if list has less than 3 strings
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download