Read case class object from string in Scala (something like Haskell's “read” typeclass)

后端 未结 6 974
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 20:32

I\'d like to read a string as an instance of a case class. For example, if the function were named \"read\" it would let me do the following:

case class Pers         


        
6条回答
  •  情深已故
    2020-12-13 21:04

    Starting Scala 2.13, it's possible to pattern match a Strings by unapplying a string interpolator:

    // case class Person(name: String, age: Int)
    "Person(Bob,42)" match { case s"Person($name,$age)" => Person(name, age.toInt) }
    // Person("Bob", 42)
    

    Note that you can also use regexes within the extractor.

    Which in this case, helps for instance to match on "Person(Bob, 42)" (age with a leading space) and to force age to be an integer:

    val Age = "[ ?*](\\d+)".r
    
    "Person(Bob, 42)" match {
      case s"Person($name,${Age(age)})" => Some(Person(name, age.toInt))
      case _ => None
    }
    // Person = Some(Person(Bob,42))
    

提交回复
热议问题