Reputation: 201
i wonder if i can change the implementation of such a method:
def foo() {
val json : String = ; // get json from somewhere
val jsonAst = new String(json).parseJson // or JsonParser(source)
val msg = jsonAst.convertTo[UserDetails]
}
so i can provide the "UserDetails" as parameter
so calling foo will be something like:
foo[UserDetails]()....
by the way:
convertTo signature is:
def convertTo[T :JsonReader]: T = jsonReader[T].read(this)
trait JsonReader[T] {
def read(json: JsValue): T
}
Upvotes: 1
Views: 101
Reputation: 46
Dima's solution should be working, but your implementation of convertTo seems strange. I think it should be something like :
def convertTo[T :JsonReader]: T = implicitly[JsonReader[T]].read(this)
Upvotes: 0
Reputation: 40510
You should be able to just declare your function the same way:
def foo[T : JsonReader] = {
...
val msg = jsonAst.convertTo[T]
}
UPDATE To elaborate, since there appears to be some confusion in the comments. def foo[T : JsonReader]
does not mean that it accepts only subclasses of JsonReader
. That declaration is actually equivalent to this: def foo[T](implicit jsonReader: JsonReader[T])
Upvotes: 2