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

后端 未结 6 946
佛祖请我去吃肉
佛祖请我去吃肉 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:14

    The answers on this question are somewhat outdated. Scala has picked up some new features, notably typeclasses and macros, to make this more easily possible.

    Using the Scala Pickling library, you can serialize/deserialize arbitrary classes to and from various serialization formats:

    import scala.pickling._
    import json._
    
    case class Person(name: String, age: Int)
    val person1 = Person("Bob", 42)
    val str = person1.pickle.value // { tpe: "Person", name: "Bob", age: 42 }
    val person2 = JSONPickle(str).unpickle[Person]
    
    assert(person1 == person2) // Works!
    

    The serializers/deserializers are automatically generated at compile time, so no reflection! If you need to parse case classes using a specific format (such as the case class toString format), you can extend this system with your own formats.

提交回复
热议问题