sirthias / borer

Efficient CBOR and JSON (de)serialization in Scala
https://sirthias.github.io/borer/
Mozilla Public License 2.0
220 stars 13 forks source link

Option to always derive `enum`s as if they were `sealed trait`s #710

Open mrdziuban opened 2 months ago

mrdziuban commented 2 months ago

Hi, thank you for this great library!

I'm curious if you would consider adding an option to always derive enums as if they were sealed traits/sealed abstract classes? That is, even a simple enum with only singleton cases would still produce a JSON object and could be configured with AdtEncodingStrategy.

For example:

import io.bullet.borer.{Encoder, Json}
import io.bullet.borer.derivation.MapBasedCodecs.*

enum Foo derives Encoder {
  case Bar
}
Json.encode(Foo.Bar).toUtf8String // "Bar"

sealed trait Baz derives Encoder.All
object Baz {
  case object Quux extends Baz
}
Json.encode(Baz.Quux: Baz).toUtf8String // {"Quux":{}}

I would like Json.encode(Foo.Bar) to produce {"Baz":{}} so I can use enums and sealed traits interchangeably

sirthias commented 2 months ago

Thanks, @mrdziuban, for this proposal. I was thinking about the distinction between enum instances and singleton objects myself. Conceptionally they are pretty much the same but technically they are very different, which case objects defining their own type extending Product0 while enum cases simply being instances of their enum type.

If we were to implement the option you are asking for it'd have to be opt-in configurable, since we can't break existing encodings. One way could be to add a enumCasesAsProduct flag to AdtEncodingStrategy. Would sth like that work for you?

mrdziuban commented 2 months ago

Yeah a new config option on AdtEncodingStrategy would be great, thank you!