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 Person(name: String, age: Int)
val personString: String = "Person(Bob,42)"
val person: Person = read(personString)
This is the same behavior as the read typeclass in Haskell.
dflemstr answered more towards setting up the actual
readmethod- I’ll answer more for the actual parsing method.My approach has two objects that can be used in scala’s pattern matching blocks.
AsIntlets you match against strings that representInts, andPersonStringis the actual implementation forPersondeserialization.The magic is in the
unapplymethod, which scala has syntax sugar for. So using thePersonStringobject, you could door you could use a pattern matching block to do stuff with the person: