0

Let say I have a list of strings:

val myList: List[String] = List("A", "B", "C") 

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

case class MyClass(name1: String, name2: String, name3: String) val result: MyClass = myList.asInstanceOf[MyClass] 
3
  • you will get a class cast exception if you do it Commented Aug 31, 2016 at 10:01
  • why do you have to type cast .. what is the purpose Commented Aug 31, 2016 at 10:02
  • 1
    case class MyClass(names: List[String]) and pass the list. Commented Aug 31, 2016 at 10:03

1 Answer 1

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

2 Comments

Should have Nil not _ so it matches exactly 3 strings in the List
@TheArchetypalPaul Fixed!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.