Skip to content

Instantly share code, notes, and snippets.

@kevinmeredith
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save kevinmeredith/8968717 to your computer and use it in GitHub Desktop.

Select an option

Save kevinmeredith/8968717 to your computer and use it in GitHub Desktop.
Why does this work if Writes[Parent] should only be implicit?
// Parent.java
public class Parent {
private String name;
private Child child;
public Parent(String name, Child child) {
this.name = name;
this.child = child;
}
public String getName() {
return name;
}
public Child getChild() {
return this.child;
}
}
// Child.java
public class Child {
private int age;
public Child(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
}
// ReadsWritesImplicits.scala
implicit val ChildReads: Reads[Child] =
(JsPath \ "age").read[Int].map{x: Int => new Child(x)}
implicit val ChildWrites: Writes[Child] =
(JsPath \ "age").write[Int].contramap{x: Child => x.getAge}
implicit val ParentFormat: Format[Parent] = (
(JsPath \ "name").format[String] and
(JsPath \ "child").format[Child]
)(parentRead, unlift(parentWrite))
// Test.scala (ScalaTest)
"converting Parent to JsValue" should "output the Child as well" in {
val parent: Parent = new Parent("Kevin", new Child(100))
val parentJson: JsValue = Json.toJson(parent)
val expected = Json.parse("""{"name":"Kevin","child":{"age":100}}""")
assert(parentJson == expected)
}
@mandubian

Copy link
Copy Markdown

because Child doesn't inherit Parent!
variance only applies on inheritance (and inheritance is just a pain :D)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment