0

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?

1

1 Answer 1

6

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

2 Comments

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?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.