I would like to write a function that transforms case classes to Json:
import play.api.libs.json._
def myJson(cc: Product): JsValue = {
Json.toJson(cc) // simplified
}
Each case class has an implicit Writes[T]
, for example:
case class Test(a: Int)
object Test {
implicit val jsonWrites: Writes[Test] = Json.writes[Test]
}
It is possible to write Json.toJson(new Test(1))
individually, but the myJson
function above does not compile because it never knows if cc
has an implicit Writes defined.
[How can I write the function signature so that it takes only classes having a Writes
implicit?]
Edit: How can I write the function input type so that it corresponds only to classes having a Writes
implicit?
I tried this:
trait JsonWritableResult[T <: Product] {
implicit val jsonWrites: Writes[T]
}
case class Test(a: Int)
object Test extends JsonWritableResult[Test] {
implicit val jsonWrites: Writes[Test] = Json.writes[Test]
}
def myJson(cc: JsonWritableResult[_ <: Product]): JsValue = {
Json.toJson(cc)
}
But it says "No Json serializer found for type models.JsonWritableResult[_$2]".
(implicit writes: Writes[T])
in yourmyJson
method. What does it mean ? You are requiring the compiler to check whether the provided type has an instance ofWrites
- Louis F.Json.toJson
already has. What I really need is a trait/type that I can give to all results of a factory so that they are guaranteed to be valid arguments totoJson
. Looks like the question was asked badly :( - JulienD