此编译 。 (请注意,implicit val subscriptionReads
组成emailIdReads
和intervalReads
声明在之外隐式,而subscriptionWrites
由Writes
组成声明里面隐含。)
import play.api.libs.json.Reads._
import play.api.libs.json.Writes._
import play.api.libs.json._
import play.api.libs.functional.syntax._
case class Subscription(emailId: String, interval: String)
object Subscription {
val emailIdReads: Reads[String] = (JsPath \ "emailId").read[String]
val intervalReads: Reads[String] = (JsPath \ "interval").read[String]
implicit val subscriptionReads: Reads[Subscription] = (
emailIdReads and
intervalReads
)(Subscription.apply _)
implicit val subscriptionWrites: Writes[Subscription] = (
(JsPath \ "emailId").write[String] and
(JsPath \ "interval").write[String]
)(unlift(Subscription.unapply))
}
下面的代码 - 两个Writes
值声明 在之外隐式 - 无法编译 ,产生错误消息:"值and
不是play.api.libs.json.Writes [String]的成员。"
import play.api.libs.json.Reads._
import play.api.libs.json.Writes._
import play.api.libs.json._
import play.api.libs.functional.syntax._
case class Subscription(emailId: String, interval: String)
object Subscription {
val emailIdReads: Reads[String] = (JsPath \ "emailId").read[String]
val intervalReads: Reads[String] = (JsPath \ "interval").read[String]
implicit val subscriptionReads: Reads[Subscription] = (
emailIdReads and
intervalReads
)(Subscription.apply _)
val emailIdWrites: Writes[String] = (JsPath \ "emailId").write[String]
val intervalWrites: Writes[String] = (JsPath \ "interval").write[String]
implicit val subscriptionWrites: Writes[Subscription] = (
emailIdWrites and
intervalWrites
)(unlift(Subscription.unapply))
}
我错过了什么?为什么我不能用等于平等的替代品?此外,为什么我可以使用Reads
而不是Writes
来执行此操作。我想了解为什么这不起作用。
and
的相关定义载于play.api.libs.functional
。
package play.api.libs.functional
import scala.language.higherKinds
case class ~[A, B](_1: A, _2: B)
trait FunctionalCanBuild[M[_]] {
def apply[A, B](ma: M[A], mb: M[B]): M[A ~ B]
}
class FunctionalBuilderOps[M[_], A](ma: M[A])(implicit fcb: FunctionalCanBuild[M]) {
def ~[B](mb: M[B]): FunctionalBuilder[M]#CanBuild2[A, B] = {
val b = new FunctionalBuilder(fcb)
new b.CanBuild2[A, B](ma, mb)
}
def and[B](mb: M[B]): FunctionalBuilder[M]#CanBuild2[A, B] = this.~(mb)
}
/* Additional arities elided */
答案 0 :(得分:2)
我不得不挖掘一点,原因实际上是在这个文件中定义了必需的隐含:
它定义为OWrites not Writes类型。你从.write [String]得到的实际上是OWrites [String]类型。它不起作用的原因是,您明确指定了更宽的类型Writes。