Possible Duplicate:
How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?
I ran the following code:
scala> var s = new Stack()push(1)
s: scalatest.Stack[Int] = 1
scala> s match { case s : Stack[String] => print("Hello")}
<console>:12: warning: non variable type-argument String in type pattern scalatest.Stack[String] is unchecked since it is eliminated by erasure
s match { case s : Stack[String] => print("Hello")
}
Stack is the class taken from http://www.scala-lang.org/node/129. If I run this code without -unchecked flag it will print “Hello”. Why is that the case?
The problem is that you’re matching
sto be of typeStack[String]. During runtime, it’s possible to determine ifsis of typeStack, but because of Java’s type erasure it’s not possible to determine ifsis of typeStack[String],Stack[Int]etc. So no matter what the type parameter was, it gets matched by thecaseexpression. This is why Scala issues the warning. It is the same as if you match as(which will compile without warnings).
Edit: A workaround (for Java too) is to create a specific class that doesn’t have type parameters any more. For example:
It has a drawback that you cannot use it for immutable containers, because their methods create new objects and they won’t be instances of these our specific subclasses.