scala - Type parameterization and strange cast exception -


i have following code splits array array of arrays before element satisfies predicate p. type checks:

def splitbefore[t](a: array[t], p: (t) => boolean)       (implicit tct: classtag[t]): array[array[t]] =   a.foldleft(array[array[t]](array.empty[t])) { (acc: array[array[t]], s: t) => if (p(s))   acc :+ array(s) else   acc.init :+ (acc.last :+ s) } 

it works fine when call non-empty a:

scala> splitbefore(array("a", "bc", "d"), (s: string) => s.size > 1) res1: array[array[string]] = array(array(a), array(bc, d)) 

but when call empty array, classcastexception:

scala> splitbefore(array.empty[string], (s: string) => s.size > 1) java.lang.classcastexception: [ljava.lang.object; cannot cast [[ljava.lang.string;   ... 33 elided 

when hand-inline call there no type parameterization, works fine:

scala> array().foldleft(array(array.empty[string])) {      |   (acc: array[array[string]], s: string) => if (s.size > 1)      |     acc :+ array(s)      |   else      |     acc.init :+ (acc.last :+ s)      | } res1: array[array[string]] = array(array()) 

any idea what's going on here? i'm using scala 2.11.7.

looks instantiating nested array causes bug - crashes on such small example:

def instantiate[a](ununsed_arg: array[t])(implicit tag: classtag[a]) =   array[array[a]](array.empty[a]) 

as quick workaround, might use arraybuilder create array:

def instantiate[t](a: array[t])(implicit ctc: classtag[t]) = {   val builder = arraybuilder.make[array[t]]   builder += array.empty[t]   builder.result } 

also please note snippet directly appends elements array, bad idea because has create new array 1 more slot , copy element. looks should either use arraybuilder or arraybuffer processing or build new data structure out of lists , convert them arrays @ end.


Comments