iyerland
iyerland

Reputation: 642

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]() = {
   ...
}

Upvotes: 0

Views: 80

Answers (1)

cchantep
cchantep

Reputation: 9168

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))

    ...
}

Upvotes: 2

Related Questions