Scala type erasure for pattern matching -
Scala type erasure for pattern matching -
i have been searching forum , google answers type erasure issues scala. however, cannot find answers question.
i struggling pattern matching on objects match type parameter of paramclass. need pattern match on type of incoming objects bar method. have seen solutions such as
bar[x](a : x)(implicit m : manifest[x])
which solve problem, cannot utilize bar method overridden method. (actually receive partial function in akka actor framework). code given below , should self explanatory:
class paramclass[a : manifest] { def bar(x : any) = x match { case a: => println("found a: " + a) case _ => println("no match: " + x) } } object erasureissue { def main(args: array[string]) { val clz = new paramclass[int] clz.bar("faf") clz.bar(2.3) clz.bar(12) // should match, not } } erasureissue.main(null)
any help on solving issue appreciated. i'm using scala 2.9.1, btw.
-j
in theory check in bar
this: x.getclass == implicitly[manifest[a]].erasure
, fails primitive types such int
manifest correctly erases int
, bar
called boxed type java.lang.integer
... :-(
you require a
anyref
in order boxed manifest:
class paramclass[a <: anyref : manifest] { def bar(x : any) = x match { case _ if x.getclass == implicitly[manifest[a]].erasure => println("found a: " + x.asinstanceof[a]) case _ => println("no match: " + x) } } object erasureissue { def main(args: array[string]) { val clz = new paramclass[integer] // not pretty... clz.bar("faf") clz.bar(2.3) clz.bar(12) // ok } } erasureissue.main(null)
given requirement build primitive arrays, store straight boxed class, independently of unboxed manifest:
object paramclass { def apply[a](implicit mf: manifest[a]) = { val clazz = mf match { case manifest.int => classof[java.lang.integer] // boxed! case manifest.boolean => classof[java.lang.boolean] case _ => mf.erasure } new paramclass[a](clazz) } } class paramclass[a] private[paramclass](clazz: class[_])(implicit mf: manifest[a]) { def bar(x : any) = x match { case _ if x.getclass == clazz => println("found a: " + x.asinstanceof[a]) case _ => println("no match: " + x) } def newarray(size: int) = new array[a](size) override def tostring = "paramclass[" + mf + "]" } val pi = paramclass[int] pi.bar("faf") pi.bar(12) pi.newarray(4) val ps = paramclass[string] ps.bar("faf") ps.bar(12) ps.newarray(4)
scala pattern-matching type-erasure
Comments
Post a Comment