Last active
August 29, 2015 13:56
-
-
Save kevinmeredith/8968717 to your computer and use it in GitHub Desktop.
Why does this work if Writes[Parent] should only be implicit?
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
| // 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) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
because Child doesn't inherit Parent!
variance only applies on inheritance (and inheritance is just a pain :D)