I am reading documentation for µPickle and searching the internet, but I was not able to find any mentions of one feature which is quite basic and I remember having it documented for perhaps all serialization libraries I was using before (Jackson, Prickle ...): polymorphic types. The only documentation I have found is for sealed traits / classes. Consider following code:
import upickle.default._
trait Base
object Base{
implicit val rw: ReadWriter[Base] = ReadWriter.merge(C1.rw, C2.rw)
}
object C1 {
implicit val rw: ReadWriter[C1] = macroRW
}
object C2 {
implicit val rw: ReadWriter[C2] = macroRW
}
case class C1(x: Int) extends Base
case class C2(s: String) extends Base
object Main extends App {
val c1: Base = new C1(0)
val c2: Base = new C2("X")
val c1String = write(c1)
val c2String = write(c2)
println("c1 " + c1String)
println("c2 " + c2String)
}
This code would work if I changed trait Base
to sealed trait Base
. I am fine with the requirement to list all derived classes in the serializer, this is what the other libraries I have mentioned required as well, but it is not always possible or desirable to have multiple large classes in one source file so that the base can be sealed. How can one serialize polymorphic types with uPickle if the base is not sealed?