简体   繁体   中英

Scala : Trying to generalize a method using generic types

So, I have this method (in 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))

    ...
}

I also have these implicits in scope:

implicit val fooFormat = Json.format[Foo]
implicit val barFormat = Json.format[Bar]

So, I thought I would refactor and create a common method, like so:

def toHttpResponse[T](entity: T) = {
   case Ok =>
     Ok(Json.toJson(entity))

    ...
}

and ...now I'm getting these errors, even when the above implicits are in scope:

No Json serializer found for type T. Try to implement an implicit Writes or Format for this type.

What am I missing? I know its something to do with these implicits! Pointers appreciated. Thanks

Updated: Answer This suggestion by [Luis Miguel Mejía Suárez] worked like a charm:

def toHttpResponse[T : Writes]() = {
   ...
}

A Writes instance must be resolved from the implicit scope:

def toHttpResponse[T](entity: T)(implicit w: Writes[T]) = {
   case Ok =>
     Ok(Json.toJson(entity))

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM