play-json-derived-codecs
play-json-derived-codecs copied to clipboard
Formatters for an ADT needs to be placed after all instances
trafficstars
The following code fails to compile with a could not find Lazy implicit value of type julienrf.json.derived.DerivedReads[A]:
import julienrf.json.derived
import play.api.libs.json._
sealed trait Minimize
object Minimize {
implicit val formats: OFormat[Minimize] = derived.flat.oformat((__ \ "type").format[String])
}
case class MinimizeA(a: String) extends Minimize
case class MinimizeB(b: Int) extends Minimize
The following code compiles successfully:
import julienrf.json.derived
import play.api.libs.json._
sealed trait Minimize
case class MinimizeA(a: String) extends Minimize
case class MinimizeB(b: Int) extends Minimize
object Minimize {
implicit val formats: OFormat[Minimize] = derived.flat.oformat((__ \ "type").format[String])
}
As there is a workaround, this is not a critical bug, but it felt like a "gotcha" moment.
If I remember well it’s a limitation of knownDirectSubclasses. I think this PR https://github.com/scala/scala/pull/5284 fixed the issue, though. Are you using Scala 2.12?