Skip to content

Instantly share code, notes, and snippets.

@salanki
Last active August 26, 2022 00:39
Show Gist options
  • Save salanki/95f792e3c7b9b236e0f4 to your computer and use it in GitHub Desktop.
Save salanki/95f792e3c7b9b236e0f4 to your computer and use it in GitHub Desktop.
Coproduct Encoder for Argonaut
import shapeless.{Poly1, Coproduct}
import shapeless.ops.coproduct.Folder
import argonaut.{_}
import argonaut.Argonaut._
/**
* Generic encoder for Coproducts, will only resolve if all types in a Coproduct has an EncodeJson in scope
*/
object CoproductToArgonautFolder extends Poly1 {
implicit def caseAnyJsonable[A: EncodeJson] = at[A](_.asJson)
}
implicit def coproductEncode[A <: Coproduct, Out <: Json](implicit fldr: Folder.Aux[CoproductToArgonautFolder.type, A, Out]): EncodeJson[A] =
EncodeJson(_.fold(CoproductToArgonautFolder))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment