zio-json icon indicating copy to clipboard operation
zio-json copied to clipboard

Support Scala 3 Union Types

Open bertlebee opened this issue 2 years ago • 4 comments

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

bertlebee avatar Oct 14 '22 08:10 bertlebee

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

Iltotore avatar Oct 25 '22 09:10 Iltotore

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.

bertlebee avatar Oct 27 '22 01:10 bertlebee

Implemented by macros here. For reference only liewhite/json

liewhite avatar Nov 19 '22 17:11 liewhite

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

Iltotore avatar Nov 19 '22 18:11 Iltotore