zio / zio-json

Fast, secure JSON library with tight ZIO integration.
https://zio.dev/zio-json
Apache License 2.0
410 stars 146 forks source link

Support Scala 3 Union Types #752

Open bertlebee opened 2 years ago

bertlebee commented 2 years ago

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

Iltotore commented 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

bertlebee commented 2 years ago

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.

liewhite commented 1 year ago

Implemented by macros here. For reference only liewhite/json

Iltotore commented 1 year ago

Here is another example using a more "mirror-like" mechanism: https://gist.github.com/Iltotore/eece20188d383f7aee16a0b89eeb887f/#file-ziojson-sc