com-lihaoyi / upickle

uPickle: a simple, fast, dependency-free JSON & Binary (MessagePack) serialization library for Scala
https://com-lihaoyi.github.io/upickle
MIT License
707 stars 158 forks source link

Case class deserialization doesn't go through `apply` in Scala 3 #552

Open smarter opened 5 months ago

smarter commented 5 months ago

https://com-lihaoyi.github.io/upickle/#Basics says:

Case classes are serialized using the apply and unapply methods on their companion objects.

This isn't the case in Scala 3:

case class Foo(x: Int) derives ReadWriter
object Foo:
  def apply(x: Int): Foo =
    assert(x > 0)
    new Foo(x)
@main def Test =
  read[Foo]("""{"x":-1}""") // Successfully constructs a Foo.

This is because deserialization uses Mirror#fromProduct which just calls the constructor: https://github.com/com-lihaoyi/upickle/blob/6e551ac735781b2921913108d5377ceccd7bbed5/upickle/implicits/src-3/upickle/implicits/Readers.scala#L72