Generic function with implicit argument

I am trying to generalize one of the functions that I am using to return Json from a Play activity.

Now I do it like this:

def JsendOkObj(obj: JsValue) = Ok(Json.obj("status" -> "success", "data" -> obj))

      

and call it:

JsendOkObj(Json.toJson(myObj))

      

I would like to do something more:

def JsendOkObj[A](obj: A) = Ok(Json.obj("status" -> "success", "data" -> Json.toJson(obj)))

      

and then call it like this:

JsendOkObj(myObj)

      

where is Json.toJson

defined as:

def toJson[A](implicit arg0: Writes[A]): Enumeratee[A, JsValue]

      

The error I am getting is that I need to define Writes for the type A

. This cannot be done, since I do not know which type A

will actually be the following:

There is no Json desantializer for type A. Try implementing implicit Writes or Format for that type.

+3


source to share


1 answer


You can ensure that the implicit Writes[A]

is in scope when called toJSon

by adding a list of implicit parameters to your own method, for example:

def JsendOkObj[A](obj: A)(implicit w: Writes[A]) =
  Ok(Json.obj("status" -> "success", "data" -> Json.toJson(obj)))

      

This is equivalent to passing an instance of the type class explicitly to toJSon

:

def JsendOkObj[A](obj: A)(implicit w: Writes[A]) =
  Ok(Json.obj("status" -> "success", "data" -> Json.toJson(obj)(w)))

      



Note that you can use contextual binding here as well :

def JsendOkObj[A: Writes](obj: A) =
  Ok(Json.obj("status" -> "success", "data" -> Json.toJson(obj)))

      

This is just syntactic sugar for my first version above.

+12


source







All Articles