zio/zio-json

Automatic derivation of codecs fails for nested HKT if implicits are defined in wrong order

p3et opened this issue · 1 comments

p3et commented

Hello. I'm pretty new to Scala and ZIO so I hope my report is qualified. Here is a minimal example to reproduce a suspected bug, that I coincidentally discovered in a more complex scenario:

import zio.ZIO
import zio.json.{DeriveJsonEncoder, EncoderOps, JsonEncoder}
import zio.test._

object EncodeJsonSpec extends ZIOSpecDefault {
  case class A()
  case class B(option: Option[A])

  implicit val aEncoder: JsonEncoder[A] = DeriveJsonEncoder.gen
  implicit val bEncoder: JsonEncoder[B] = DeriveJsonEncoder.gen
  implicit val aOptionEncoder: JsonEncoder[Option[A]] = DeriveJsonEncoder.gen

  def spec =
    suite("JsonSpec")(
      test("Encode JSON") {
        for {
          json <- ZIO.attempt(B(option = Some(A())).toJson)
        } yield assertTrue(json != null)
      }
    )
}

The test can be easily fixed by defining the implicits in the order aEncoder, aOptionEncoder, bEncoder. However, the problem seems to be specifically related to HKT because using aOptionEncoder, bEncoder, aEncoder won't cause a problem although A is nested in B.

I would expect that, if the order of definitions matters, there will be a compile or build error. However, the error occurs only at runtime.

Scala 2.13.11
zio 2.0.16
zio-json 0.6.1