Scala Generics : Cannot write an instance of T to HTTP response. Try to define a Writeable[T] -
following code when written using generic give compilation error.
without generic
def getdata(id: string) = action.async { val items = getitems(id) sendresult(items) } private def sendresult(result: future[any]) = { result.map { items => { try { val itemstr = items.asinstanceof[string] ok(itemstr) } catch { case t: classcastexception => internalservererror(s"casting exception while processing output $t") } } }.recover { case t:timeoutexception => internalservererror("api timed out") case t: throwable => internalservererror(s"exception in api $t") } }
with generic
def getdata(id: string) = action.async { val items = getitems(id) sendresult[string](items) } private def sendresult[t](result: future[any]) = { result.map { items => { try { val itemstr = items.asinstanceof[t] ok(itemstr) } catch { case t: classcastexception => internalservererror(s"casting exception while processing output $t") } } }.recover { case t:timeoutexception => internalservererror("api timed out") case t: throwable => internalservererror(s"exception in api $t") } }
the code part of play app's contorller method. first 1 works fine. second 1 gives following compilation error
cannot write instance of t http response. try define writeable[t] [error] ok(itemstr) [error]
using any
generic function doesn't make sense.
private def sendresult[t](result: future[any]) // should better private def sendresult[t](result: future[t]) // ... remove unsafe cast
then t
needs provided instance of writeable
, can written array[byte]
on network.
// either ... private def sendresult[t: writeable](result: future[t]) // ... or ... private def sendresult[t](result: future[t])(implicit w: writeable[t])
Comments
Post a Comment