Scala将字符串转换为对象

时间:2019-09-25 02:49:14

标签: scala

我有类定义case class Name(firstName: String, lastName: Option[String])和字符串Name(Tom,Some(Bob)),如何将字符串转换为Name对象?

1 个答案:

答案 0 :(得分:5)

您可以使用字符串插值来解构输入字符串。 ( 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))