Skip to content

Instantly share code, notes, and snippets.

@trane
Last active September 17, 2015 16:56
Show Gist options
  • Select an option

  • Save trane/cdce3fe03f46f1de978b to your computer and use it in GitHub Desktop.

Select an option

Save trane/cdce3fe03f46f1de978b to your computer and use it in GitHub Desktop.
this is one way to handle partial case classes
import io.circe._, io.circe.generic.auto._, io.circe.jawn._, io.circe.syntax._
// define a class with default param value
case class Foo(s: String, i: Int = 10)
val json = """{"s": "Hello"}"""
val json2 = """{"s": "World", "i": 42}"""
// define some boilerplate decoders, utilizing the two constructors via decoders
val dec1 = Decoder.instance[Foo](c => for (s <- c.downField("s").as[String]; i <- c.downField("i").as[Int]) yield Foo(s, i))
val dec2 = Decoder.instance[Foo](c => for (s <- c.downField("s").as[String]) yield Foo(s))
// combine them
implicit val fooDecoder = dec1 ||| dec2
decode[Foo](json) // res0: cats.data.Xor[io.circe.Error,Foo] = Right(Foo(Hello,10))
decode[Foo](json2) // res1: cats.data.Xor[io.circe.Error,Foo] = Right(Foo(World,42))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment