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

Discriminator field is omitted when child type has its own codec #1050

Open
sergeykolbasov opened this issue Jul 7, 2023 · 1 comment
Open
Labels

Comments

@sergeykolbasov
Copy link

sergeykolbasov commented Jul 7, 2023

Simple reproduction:

https://scastie.scala-lang.org/ApPHtGwrRE2GCGUpECBGww

import com.github.plokhotnyuk.jsoniter_scala.core.*
import com.github.plokhotnyuk.jsoniter_scala.macros.*

given CodecMakerConfig.PrintCodec with {}

sealed trait Parent

object Parent {
  given JsonValueCodec[Parent] = JsonCodecMaker.make(CodecMakerConfig.withDiscriminatorFieldName(Some("type")))
}

case class Child(a: Int) extends Parent

object Child {
  given JsonValueCodec[Child] = JsonCodecMaker.make(CodecMakerConfig.withDiscriminatorFieldName(Some("type")))
}

val x: Parent = Child(42)

writeToString[Parent](x) // {"a": 42}

Expected behavior is to include a type discriminator field whenever value is encoded using a parent codec.

From what I see in the generated macro Parent codec, the encoding is fully delegated to the child codec whenever it exists, and the child codec on its own disregards the discriminator.

I'm not sure if it's a consistent behavior from the user perspective, given there is an explicit discriminator configuration set on the parent codec.

@plokhotnyuk
Copy link
Owner

plokhotnyuk commented Jul 7, 2023

Just remove all codec derivation for non top-level case classes.

Deriving codecs in companion objects is anti-pattern for jsoniter-scala:

  1. It floods data-model definition with a lot of boilerplate.
  2. It is inefficient from the point of performance view due to introducing a lot of megamorphic virtual calls for JVM interfaces.

Macros will never try to cooperate and guess your intention ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants