2014-02-06 94 views
0

我有3個case類:創建讀取的列表[案例類]

scala> case class Friend(id: Long, hobbies: List[Long]) 
defined class Friend 

scala> case class Kid(friends: List[Friend]) 
defined class Kid 

scala> case class Parent(kids: List[Kid]) 
defined class Parent 

它們可以顯示在層次結構(父母有孩子(一個或多個)的朋友(S)有(ID和愛好)。

Parent 
    ---> Kid 
     ---> Friend 
      ---> id: Long 
      ---> hobbies: List[Long] 

我創建了FriendsReads(儘管作爲senia指出here,我可能只需要使用

scala> implicit val FriendReads: Reads[Friend] = Json.format[Friend] 
FriendReads: play.api.libs.json.Reads[Friend] = [email protected] 

scala> implicit val FriendReads: Reads[Friend] = (
    | (JsPath \ "id").read[Long] and 
    | (JsPath \ "hobbies").read[List[Long]] 
    |)(Friend.apply _) 
FriendReads: play.api.libs.json.Reads[Friend] = [email protected] 

然後,當我試圖創建KidReads時,我遇到了編譯時問題。

scala> implicit val KidReads: Reads[Kid] = (
    | (JsPath \ "friends").read[List[Friend]] 
    |)(Kid.apply _) 
<console>:40: error: overloaded method value read with alternatives: 
    (t: List[Friend])play.api.libs.json.Reads[List[Friend]] <and> 
    (implicit r: play.api.libs.json.Reads[List[Friend]])play.api.libs.json.Reads[List[Friend]] 
cannot be applied to (List[Friend] => Kid) 
     (JsPath \ "friends").read[List[Friend]] 
          ^

如何解決此錯誤?

+0

謝謝,特拉維斯,你是對的。我看到一種新類型,忘記檢查你的有用答案。我的錯。 –

回答

1

表達(JsPath \ "friends").read[List[Friend]]創建Reads[List[Friend]],你可以使用map方法這樣將其轉換爲Reads[Kid]

implicit val KidReads: Reads[Kid] = 
    (JsPath \ "friends").read[List[Friend]] map Kid.apply 

功能Kid.apply將被應用到結果的Reads[List[Friend]]#reads這樣的:

val friendListReads: Reads[List[Friend]] = (JsPath \ "friends").read[List[Friend]] 

implicit val kidReads: Reads[Kid] = new Reads[Kid] { 
    def reads(json: JsValue): JsResult[Kid] = friendListReads.reads(json) match { 
    case JsSuccess(fList, path) = JsSuccess(Kid(fList), path) 
    case e: JsError => e 
    } 
} 
+0

當映射到Reads [List [Friend]]上時,映射函數f具有簽名:List [Friend] - > Friend? –

+0

@KevinMeredith:是的。 – senia

+0

我無法推理這個map函數。爲什麼將Kid.map應用於每個朋友的工作? –