Skip to content

Instantly share code, notes, and snippets.

@mandubian
Forked from playxamplez-admin/CODE
Last active February 27, 2018 15:43
Show Gist options
  • Save mandubian/6046786 to your computer and use it in GitHub Desktop.
Save mandubian/6046786 to your computer and use it in GitHub Desktop.
#Recursive class #Json #Reads using #lazyRead feature #Play21 #scala A class inheriting a parent trait with a member of the parent type
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
sealed abstract trait Tree
case class Leaf(a: String) extends Tree
case class Node(l: Tree, r: Tree) extends Tree
implicit val treeR: Reads[Tree] =
__.read[Leaf].map(x => x:Tree) orElse
(
(__ \ "l").lazyRead(treeR) and (__ \ "r").lazyRead(treeR)
)(Node.apply _).map(x => x:Tree)
scala> treeR.reads(Json.obj("a" -> "toto"))
res10: play.api.libs.json.JsResult[Tree] = JsSuccess(Leaf(toto),/a)
scala> treeR.reads(Json.obj("l" -> Json.obj("a" -> "toto"), "r" -> Json.obj("a" -> "tata")))
res11: play.api.libs.json.JsResult[Tree] = JsSuccess(Node(Leaf(toto),Leaf(tata)),)
Copy link

ghost commented Feb 27, 2018

code:

 implicit val leafReads =  ((__ \ "a").read[String] ) map ( x => Leaf(x))

 implicit val treeReads:Reads[Tree] = (__.read[Leaf]) map( x => x:Tree) orElse
     (
       ( __ \ "l").lazyRead(treeReads) and
       ( __ \ "r").lazyRead(treeReads)
    ) (Node.apply _) map (x => x:Tree)   

gives out this error :
Error:(109, 41) forward reference extends over definition of value treeReads
( __ \ "l").lazyRead(treeReads) and

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