5

鉴于以下需要对 JSON 进行序列化/反序列化的案例类...

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

trait MyTrait(s1: String, s2: String)

case class MyClass(s1: String, s2: String) extends MyTrait {

  def this(t: MyTrait) = this(t.s1, t.s2)
}

object MyClass {

  def apply(t: MyTrait) = new MyClass(t)

  implicit val myClassJsonWrite = new Writes[MyClass] {
    def writes(c: MyClass): JsValue = {
      Json.obj(
        "s1" -> c.s1,
        "s2" -> c.s2
      )
    }
  }

  implicit val myClassJsonRead = (
    (__ \ 's1).read[String] ~
    (__ \ 's2).read[String]
  )(MyClass.apply _)
}

...我总是收到以下错误消息:

[error] /home/j3d/Projects/test/app/models/MyClass.scala:52: ambiguous reference to overloaded definition,
[error] both method apply in object MyClass of type (s1: String, s2: String)models.MyClass
[error] and  method apply in object MyClass of type (t: MyTrait)models.MyClass
[error] match expected type ?
[error]   )(MyClass.apply _)
[error]             ^

...为什么编译器不推断正确的apply方法?我该如何解决这个错误?任何帮助将非常感激。谢谢。

4

1 回答 1

5

您可以像这样选择正确的方法:

MyClass.apply(_: String, _: String)

编译器无法推断出正确的类型,因为您引用了该apply方法。因为您明确引用它们,所以编译器不会为您做出选择。

为了使语法更具可读性,您可以更改伴随对象定义

object MyClass extends ((String, String) => MyClass) {

这样您就可以简单地引用伴随对象而不是模棱两可的apply方法

implicit val myClassJsonRead = (
  (__ \ 's1).read[String] ~
  (__ \ 's2).read[String])(MyClass)
于 2013-02-24T15:21:38.290 回答