scala – erasure type exception – for arrays

Theonlyexceptiontotheerasureruleisarrays,becausetheyarehandled specially in Java as well as in Scala. The element type of an array is stored with the array value, so you can pattern match on it. Here’s an example:

 

scala> def isStringArray(x: Any) = x match {

case a: Array[String] => “yes”

case _ => “no” } isStringArray: (x: Any)java.lang.String

scala> val as = Array(“abc”) as: Array[java.lang.String] = Array(abc) scala> isStringArray(as) res21: java.lang.String = yes

scala> val ai = Array(1, 2, 3) ai: Array[Int] = Array(1, 2, 3) scala> isStringArray(ai) res22: java.lang.String = no

Leave a comment