Last active
September 17, 2015 16:56
-
-
Save trane/cdce3fe03f46f1de978b to your computer and use it in GitHub Desktop.
this is one way to handle partial case classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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