Closed michaelahlers closed 6 years ago
Implicit instances for a type T
should be in the T
companion object. What happens if you move tricksFormat
into the Tricks
companion object, and dogFormat
into the Dog
companion object.
Also, direct descendents of a sealed type don’t need to have an explicit OFormat
instance (it’s derived by the library). So, you can just remove dogFormat
and tricksFormat
.
@julienrf, thanks for the quick and detailed reply! Point-by-point:
What happens if you move
tricksFormat
into theTricks
companion object, anddogFormat
into theDog
companion object?
Same result:
import julienrf.json.derived
import play.api.libs.json._
object Sample {
sealed trait Animal
object Animal {
case class Dog(name: String, age: Int, tricks: Dog.Tricks) extends Animal
object Dog {
case class Tricks(sit: Boolean, stay: Boolean)
object Tricks {
implicit val format: OFormat[Tricks] = Json.format
}
implicit val format: OFormat[Dog] = Json.format
}
implicit val format: OFormat[Animal] = derived.oformat()
}
}
[D]irect descendents of a sealed type don’t need to have an explicit
OFormat
instance (it’s derived by the library). So, you can just removedogFormat
andtricksFormat
.
This example was made simple as possible to isolate my specific complaint. 😉 In my practical case, there's customization needed along with a few Format
instances I don't control. And, ultimately, the functionality I'm after is essentially what's given by your original play-json-variants
library.
If it's all working as designed, then I think importing the necessary The secondary Format
instances into a narrow scope isn't a bad way to accomplish what I need.Format
instances are used when imported into scope, but Dog
is still derived automatically (which discards any custom serialization logic). Drat.
Turns out leonardehrenfried/play-json-traits is closer to what my project needs. Once again, @julienrf, your feedback was greatly appreciated! I'll close this since I'm basically trying to abuse your library. 😉
Given this example:
This fails to compile with:
It will compile if
import Animal.Dog.tricksFormat
is restored. I'm mystified by this. The onlyOFormat
instance that should be required can be resolved (while not imported into scope, it's provided by the companion object). Why isn'tdogFormat
enough to satisfyderived.oformat()
?