Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: JsonDiscriminator #3

Closed
wants to merge 1 commit into from

Conversation

goshacodes
Copy link
Owner

@goshacodes goshacodes commented Apr 24, 2024

Proposed feature for Scala 3:

  1. Derive JsonReader for sum types with provided implicit JsonDiscriminator.
  2. Derive JsonWriter with discriminator if JsonDiscriminator for type is in scope
trait JsonDiscriminator[A, B]:
  def choose: A => B

object JsonDiscriminator:
  def by[A, B](f: A => B): JsonDiscriminator[A, B] = new JsonDiscriminator[A, B]:
    override def choose: A => B = f
   

Example:

enum Choice(val discriminator: Int) derives JsonReader, JsonObjectWriter:
  case First(first: String) extends Choice(0)
  case Second(second: Int) extends Choice(1)

object Choice:
  given JsonDiscriminator[Choice, Int] = JsonDiscriminator.by(_.discriminator)
  


(First("123"): Choice).asJson === {"discriminator": 0, "first": "123"}

{"discriminator": 0, "first": "123"}.jsonAs[Choice] === First("123")

@goshacodes goshacodes force-pushed the json_discriminator branch 5 times, most recently from a3205c3 to 2fee09f Compare April 25, 2024 06:06
@goshacodes goshacodes changed the title json_discriminator Feature: JsonDiscriminator Apr 25, 2024
@goshacodes goshacodes force-pushed the json_discriminator branch 3 times, most recently from 8caac38 to 8044d26 Compare April 25, 2024 08:21
@goshacodes goshacodes force-pushed the json_discriminator branch from 8044d26 to 3d54231 Compare May 2, 2024 14:12
@goshacodes goshacodes closed this May 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant