[英]Scala : Trying to generalize a method using generic types
因此,我有此方法(在play framework / scala中):
def toHttpResponse(entity: Option[Foo]) = {
case Ok =>
Ok(Json.toJson(entity))
...
}
def toHttpResponse(entity: Option[Bar]): = {
case Ok =>
Ok(Json.toJson(entity))
...
}
我在范圍內也有這些隱式:
implicit val fooFormat = Json.format[Foo]
implicit val barFormat = Json.format[Bar]
因此,我想我將重構並創建一個通用方法,如下所示:
def toHttpResponse[T](entity: T) = {
case Ok =>
Ok(Json.toJson(entity))
...
}
並且...現在,即使上述隱式在范圍內,我也會遇到這些錯誤:
No Json serializer found for type T. Try to implement an implicit Writes or Format for this type.
我想念什么? 我知道這與這些隱式有關! 指針表示贊賞。 謝謝
更新:答案[路易斯·米格爾·梅賈·蘇亞雷斯]的建議很吸引人:
def toHttpResponse[T : Writes]() = {
...
}
必須從隱式范圍解析Writes
實例:
def toHttpResponse[T](entity: T)(implicit w: Writes[T]) = {
case Ok =>
Ok(Json.toJson(entity))
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.