我有类定义case class Name(firstName: String, lastName: Option[String])
和字符串Name(Tom,Some(Bob))
,如何将字符串转换为Name
对象?
答案 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))