当在 Scala 中期望隐式时,参数多态性会中断
Parametric polymorphism breaks when an implicit is expected in Scala
我明白了
No Json serializer found for type T. Try to implement an implicit Writes or Format for this type.
在
import play.api.libs.json._
trait A[T] {
def foo(t: T) = bar(Json.toJson(t))
}
我将为 actual 参数类型设置一个 Writes
,但我认为这不会清除编译错误。经过一些谷歌搜索,我觉得我对这个主题的理解可能缺少一些基本的东西。任何帮助表示赞赏。
在这种情况下错误信息不是很清楚——你不需要为这个类型实现一个Writes
,你只需要向编译器证明你有一个:
import play.api.libs.json._
trait A[T] {
def foo(t: T)(implicit w: Writes[T]) = bar(Json.toJson(t))
}
这将按预期工作。你也可以在特征中有一个 implicit def w: Writes[T]
,这需要实例化器提供一个实例,这更具限制性,因为你不能在没有实例的情况下实例化 A
,但它在语法上更简洁如果您有很多这样的方法,并且您实际上可能希望限制更早生效,而不是在您已经实例化了 A
并尝试调用 foo
之后它。
提供implicit def writes
import play.api.libs.json._
trait A[T] {
implicit def writes: Writes[T]
def foo(t: T) = bar(Json.toJson(t))
}
或将写入作为 implicit
参数提供给 foo
import play.api.libs.json._
trait A[T] {
def foo(t: T)(implicit writes: Writes[T]): JsValue = bar(Json.toJson(t))
}
我明白了
No Json serializer found for type T. Try to implement an implicit Writes or Format for this type.
在
import play.api.libs.json._
trait A[T] {
def foo(t: T) = bar(Json.toJson(t))
}
我将为 actual 参数类型设置一个 Writes
,但我认为这不会清除编译错误。经过一些谷歌搜索,我觉得我对这个主题的理解可能缺少一些基本的东西。任何帮助表示赞赏。
在这种情况下错误信息不是很清楚——你不需要为这个类型实现一个Writes
,你只需要向编译器证明你有一个:
import play.api.libs.json._
trait A[T] {
def foo(t: T)(implicit w: Writes[T]) = bar(Json.toJson(t))
}
这将按预期工作。你也可以在特征中有一个 implicit def w: Writes[T]
,这需要实例化器提供一个实例,这更具限制性,因为你不能在没有实例的情况下实例化 A
,但它在语法上更简洁如果您有很多这样的方法,并且您实际上可能希望限制更早生效,而不是在您已经实例化了 A
并尝试调用 foo
之后它。
提供implicit def writes
import play.api.libs.json._
trait A[T] {
implicit def writes: Writes[T]
def foo(t: T) = bar(Json.toJson(t))
}
或将写入作为 implicit
参数提供给 foo
import play.api.libs.json._
trait A[T] {
def foo(t: T)(implicit writes: Writes[T]): JsValue = bar(Json.toJson(t))
}