Skip to content

Instantly share code, notes, and snippets.

@trane
Created September 16, 2015 23:43
Show Gist options
  • Select an option

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

Select an option

Save trane/bd8a4a917b7a2efae194 to your computer and use it in GitHub Desktop.
case class Foo(s: String, i: Int = 10)
val json = """{"s": "Hello"}"""
// this obviously works
decode[Int => Foo](json).map(_(10))
// but what about cases where you have many default parameters of the same type?
case class Bar(i1: Int, i2: Int = 2, i3: Int = 3, i4: Int = 4)
val json2 = """{"i1": 1}"""
// i would like the following behavior...
"""{"i1": 1, "i4": 44}""".as[Bar] // => Bar(1, 2, 3, 44)
// this would work kind of work, but it overrides the default values
decode[(Int, Int, Int) => Bar].map(_(2, 3, 44))
// alternatively, I could do this to ignore the potentially incoming values:
val dec = Decoder.instance[Bar](c =>
for {
i1 <- c.downField("i1").as[Int]
} yield Bar(i1)
)
// or change my datatype completely:
case class Bar2(i1: Int, i2: Option[Int], i3: Option[Int], i4: Option[Int])
val dec2 = Decoder.instance[Bar2](c =>
for {
i1 <- c.downField("i1").as[Int]
i2 <- c.downField("i2").as[Option[Int]]
i3 <- c.downField("i3").as[Option[Int]]
i4 <- c.downField("i4").as[Option[Int]]
} yield Bar2(i1, i2, i3, i4)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment