Either is expecting a Right or Left as in
scala> Hi(Right("foo")).asJson
res7: io.circe.Json =
{
"s" : {
"Right" : {
"b" : "foo"
}
}
}
@danbills It's worth noting that that's kind of just an accident of auto, and you probably will generally want to use Decoder.decodeEither or Decoder#or to create explicit Either decoders.
I was able to produce the expected behavior by declaring the following decoder for Either[A,B]:
implicit def j[A,B](implicit a: Decoder[A], b: Decoder[B]): Decoder[Either[A,B]] =
new Decoder[Either[A, B]] {
final def apply(c: HCursor): Result[Either[A, B]] = {
val d = a split b
val l = d(Left(c))
val r = d(Right(c))
if (l.isLeft) r else l
}
}
or even simpler:
implicit def h[A,B](implicit a: Decoder[A], b: Decoder[B]): Decoder[Either[A,B]] = {
val l: Decoder[Either[A,B]]= a.map(Left.apply)
val r: Decoder[Either[A,B]]= b.map(Right.apply)
l or r
}
Forget about derivation, why not have it out of the box (like Option)?
Most helpful comment
Forget about derivation, why not have it out of the box (like Option)?