2014-09-13 57 views
0

我試圖理解在更深層次上寫入[T],而不僅僅是接受它的作用,而我知道它的確如此。我感到困惑的是,在應用和解除T之後,我的理解是你以價值觀念的結尾。如果它們都是相同類型,比如下面的雙倍,它如何將這些值與適當的地方相匹配?我想知道它是否與組合器的順序有關,但本地實驗似乎顯示我的順序並不重要。從ScalaJsonCombinators頁面播放文件的例子:播放JSON寫入如何將字段值獲取到正確的字段中

case class Location(lat: Double, long: Double) 

import play.api.libs.json._ 
import play.api.libs.functional.syntax._ 

implicit val locationWrites: Writes[Location] = (
(JsPath \ "lat").write[Double] and 
(JsPath \ "long").write[Double] 
)(unlift(Location.unapply)) 

回答

2

它絕對具有與組合子VS在Location.unapply領域的訂單的訂單做,否則就寫ReadsWrites沒有確定的方式。在Writes

implicit val locationWrites: Writes[Location] = (
    (JsPath \ "lat").write[Double] and 
    (JsPath \ "long").write[Double] 
)(unlift(Location.unapply)) 

scala> Json.stringify(Json.toJson(Location(2.11, 42.12))) 
res2: String = {"lat":2.11,"long":42.12} 

的路徑名是無關的Location字段名稱,它只是應用它們依次是:

// Reversed 
implicit val locationWrites: Writes[Location] = (
    (JsPath \ "long").write[Double] and 
    (JsPath \ "lat").write[Double] 
)(unlift(Location.unapply)) 

scala> Json.stringify(Json.toJson(Location(2.11, 42.12))) 
res3: String = {"long":2.11,"lat":42.12} 
+0

啊確定這是有道理的感謝! – Barry 2014-09-13 16:56:09