Circe: Auto derivation of an Either

Created on 20 Jun 2017  路  5Comments  路  Source: circe/circe

See gist.

Unless I'm missing something it seems that auto-deriving a decoder for Either isn't working.

I'm currently using a workaround of circe-shapeless and coproduct but that is suboptimal with only 2 potential types.

Most helpful comment

Forget about derivation, why not have it out of the box (like Option)?

All 5 comments

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)?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

darkfrog26 picture darkfrog26  路  4Comments

ChetanBhasin picture ChetanBhasin  路  6Comments

dwijnand picture dwijnand  路  5Comments

aesteve picture aesteve  路  4Comments

jilen picture jilen  路  3Comments