Skip to content

Instantly share code, notes, and snippets.

@gvolpe
Created December 4, 2020 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gvolpe/a68914b1c78cf49e51ebb8ec88311724 to your computer and use it in GitHub Desktop.
Save gvolpe/a68914b1c78cf49e51ebb8ec88311724 to your computer and use it in GitHub Desktop.
implicit def eitherEncoder[A: Encoder, B: Encoder]: Encoder[Either[A, B]] =
Encoder[Json].contramap[Either[A, B]](_.asJson)
implicit def eitherDecoder[A: Decoder, B: Decoder]: Decoder[Either[A, B]] =
Decoder[Json].emap[Either[A, B]] { js =>
js.as[A] match {
case Left(_) => js.as[B].map(_.asRight[A]).leftMap(_.message)
case Right(x) => Right(x.asLeft[B])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment