Scala trouble with casting to generics -
Scala trouble with casting to generics -
i tried write function different things according input type. example, this:
def foo[t](inlist: list[string]): arraybuffer[t] = { val out: arraybuffer[t] = new arraybuffer[t]() inlist.map ( x => { val str = x.substring(1) out += str.asinstanceof[t] }) out }
but if phone call function foo[long](new list("123","2342"))
, arraybuffer
string
s, not long
s. sorry noob question, want understand scala , generics.
scala runs ontop of jvm, not know generics, , concrete type of generic not available @ runtime.
so that, runtime equivalent of code
def foo(inlist: list[string]): (arraybuffer[object]) = { val out: arraybuffer[object] = new arraybuffer[object]() inlist.map ( x => { val str=x.substring(1) out += str.asinstanceof[object] }) (out) }
asinstanceof not convert strings longs, instead throw exception incompatible types. instead, should supply function conversion strings type. summing up, code should this:
import scala.collection.mutable.arraybuffer // here define how convert string longs implicit def stringtolong(s: string) = s.tolong // function requires have converter string t in context def foo[t](inlist: list[string])(implicit f: (string) => t): (arraybuffer[t]) = { val out: arraybuffer[t] = new arraybuffer[t]() inlist.map { x => val str = x.substring(1) out += f(str) // here apply converter } out } // when function called, appropriate implicit converter context used foo[long](list("51", "42"))
scala generics casting
Comments
Post a Comment