Open bertlebee opened 2 years ago
This is unfortunately a limitation of Scala due to union type commutativity.
Taking your example:
given [A, B](using aCodec: JsonCodec[A], bCodec: JsonCodec[B]): JsonCodec[A | B] =
aCodec.asInstanceOf[JsonCodec[A | B]] <> bCodec.asInstanceOf[JsonCodec[A | B]]
sealed case class Test(
id: Int | String | Boolean
) derives JsonCodec
//Ambiguous implicit because Int | String | Boolean =:= Int | Boolean | String =:= String | Int | Boolean =:= ...
(Scastie)
This limitation is discussed in Scala Contributors
I found this after I created this issue https://github.com/iRevive/union-derivation I'm not sure what the policy on external library dependencies are here but I think it's small enough and low enough effort to perhaps just subsume it into zio-json like izumi reflect ended up in zio.
edit: perhaps this should go into zio instead - the whole ecosystem would benefit then. I'll create an issue there instead, but will leave this open as there will probably be some minimal work to do once it's in zio.
Implemented by macros here. For reference only liewhite/json
Here is another example using a more "mirror-like" mechanism: https://gist.github.com/Iltotore/eece20188d383f7aee16a0b89eeb887f/#file-ziojson-sc
Scala 3 union types aren't supported, but unions are very common in typescript - support for this would be super handy!
https://scastie.scala-lang.org/1h8VItvQQdiuZpGR4EX0qg