I have class definition case class Name(firstName: String, lastName: Option[String]) and a string Name(Tom,Some(Bob)), how can I convert the string to a Name object?
-
1Refer: stackoverflow.com/questions/10804581/…hagarwal– hagarwal2019-09-25 03:06:10 +00:00Commented Sep 25, 2019 at 3:06
Add a comment
|
1 Answer
You can use string interpolation to deconstruct the input string. (Scala 2.13.0)
case class Name(firstName: String, lastName: Option[String])
val str = "Name(Tom,Some(Bob))"
val nm :Name = str match {
case s"Name($fn,Some($ln))" => Name(fn, Some(ln))
case s"Name($fn,None)" => Name(fn, None)
case _ => throw new Error("not a name")
}
//nm: Name = Name(Tom,Some(Bob))
2 Comments
coderz
If my class contains
Seq like case class User(firstName: String, lastName: Option[String], addresses: Seq[Address]), it will be difficult to assemble the regex because count of Address is unknown, any good idea to solve this problem?jwvh
You appear to be looking for an
eval() function, i.e. something like myCodeRslt = eval(myString) Scala can't do that. To get close you'd probably have to write a macro after digging in to the reflection library. Easier to simply switch to a different language.