为什么Scala编译器会不同地处理这两个代码块?

时间:2016-02-12 00:54:49

标签: json scala playframework

此编译 。 (请注意,implicit val subscriptionReads组成emailIdReadsintervalReads声明之外隐式,而subscriptionWritesWrites组成声明里面隐含。)

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 */

1 个答案:

答案 0 :(得分:2)

我不得不挖掘一点,原因实际上是在这个文件中定义了必需的隐含:

https://github.com/playframework/playframework/blob/26a9c7625d6c482abf1c6ecedacff34d670bee01/framework/src/play-json/src/main/scala/play/api/libs/json/Writes.scala

它定义为OWrites not Writes类型。你从.write [String]得到的实际上是OWrites [String]类型。它不起作用的原因是,您明确指定了更宽的类型Writes。