给出以下需要对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
方法?我怎么能修复这个错误?任何帮助将非常感激。感谢。
答案 0 :(得分:4)
您可以选择正确的方法:
MyClass.apply(_: String, _: String)
编译器无法推断出正确的类型,因为您引用了apply
方法。因为您明确引用它们,编译器不会为您做出选择。
为了使语法更具可读性,您可以更改伴随对象定义
object MyClass extends ((String, String) => MyClass) {
这样您就可以简单地引用伴随对象而不是模糊的apply
方法
implicit val myClassJsonRead = (
(__ \ 's1).read[String] ~
(__ \ 's2).read[String])(MyClass)