如何play.api.libs.Reads为People案例类创建一个?
play.api.libs.Reads
People
scala> type Id = Long defined type alias Id scala> case class People(names: Set[Id]) defined class People scala> implicit val PeopleReads: Reads[People] = ( | (__ \ "names").read[Set[Id]])(People) <console>:21: error: overloaded method value read with alternatives: (t: Set[Id])play.api.libs.json.Reads[Set[Id]] <and> (implicit r: play.api.libs.json.Reads[Set[Id]])play.api.libs.json.Reads[Set[Id]] cannot be applied to (People.type) (__ \ "names").read[Set[Id]])(People)
该(...)(People)语法是为您使用构造参数列表(嗯,从技术上讲,它是一个Builder,而不是列表)而设计的,and并希望将People构造函数提升到应用函子中,Reads以便可以将其应用于这些参数。
(...)(People)
Builder
and
Reads
例如,如果您的People类型如下所示:
case class People(names: Set[Id], home: String)
您可以这样写:
implicit val PeopleReads: Reads[People] = ( (__ \ "names").read[Set[Id]] and (__ \ "home").read[String] )(People)
但是,在您的情况下,for的构造函数People只有一个参数,并且您没有使用过and,所以您没有a Builder[Reads[Set[Id] ~ String],您只是拥有一个普通的old Reads[Set[Id]]。
Builder[Reads[Set[Id] ~ String]
Reads[Set[Id]]
很好,因为它意味着您不需要怪异的应用函子语法,而您所需要的只是map:
map
implicit val PeopleReads = (__ \ "names").read[Set[Id]].map(People)
这样就完成了。