plokhotnyuk / jsoniter-scala

Scala macros for compile-time generation of safe and ultra-fast JSON codecs + circe booster
MIT License
750 stars 99 forks source link

sumtype with discriminator based on a common field #1203

Closed lenguyenthanh closed 2 months ago

lenguyenthanh commented 2 months ago

let me go directly to the examples,

  enum Client(@named("t") val tpe: String):
    case Ping(@named("l") timestamp: Long) extends ClientOut("p")
    case Move(@named("m") move: Long) extends ClientOut("m")

  import Client.*

  given JsonValueCodec[ClientOut] = ???

  // I hope to get this:
  assert(writeToString(Ping(1), "{"t":"p","l":1}")
  assert(writeToString(Move(1), "{"t":"p","m":1}")

My goal is discriminate sum types based on a common fields. I tried few experiment with CodecMakerConfig but doesn't seem to work.

I think I could make custom Codec for each case, but in this situation, I have a lot of case like this so I would love to have it derives automatically for me.

plokhotnyuk commented 2 months ago

@lenguyenthanh Thanks for trying and your feedback!

I've committed one of the possible solutions using @transient annotation for tpe and @named annotations for leaf enum classes.

Please check if it will be acceptable for you.

lenguyenthanh commented 2 months ago

Thanks @plokhotnyuk a lot, your solution works for my case. There is a bit of duplication there, but it's more than good enough!