j3d*_*j3d 5 scala playframework-2.0
给定以下需要对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 _)
}
Run Code Online (Sandbox Code Playgroud)
...我总是收到以下错误消息:
[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] ^
Run Code Online (Sandbox Code Playgroud)
...为什么编译器不推断正确的apply方法?我怎么能修复这个错误?任何帮助将非常感激.谢谢.
您可以像这样选择正确的方法:
MyClass.apply(_: String, _: String)
Run Code Online (Sandbox Code Playgroud)
编译器无法推断正确的类型,因为您引用了该apply方法。因为您明确引用它们,编译器不会为您做出选择。
为了使语法更具可读性,您可以更改伴随对象定义
object MyClass extends ((String, String) => MyClass) {
Run Code Online (Sandbox Code Playgroud)
这样你就可以简单地引用伴随对象而不是模棱两可的apply方法
implicit val myClassJsonRead = (
(__ \ 's1).read[String] ~
(__ \ 's2).read[String])(MyClass)
Run Code Online (Sandbox Code Playgroud)