@specialized has nothing to do with type erasure, at least in this case. This means that an additional version of your class is generated with a native type in position. This is especially noticeable when boxing / unpacking.
So you define a class like:
class MyClass[@specialized(Int) T] { def foobar(t: T) = {} }
and you will get two classes as output, (approximately):
class Foobar[java.lang.Object] { def foobar(t: java.lang.Object) = {} } class Foobar[int] { def foobar(t: int) = {} }
You need to have two class implementations, because you cannot always guarantee that someone who has the correct native type will be called. The scala compiler will choose which one to invoke. Please note that the java compiler has no idea that this specialization takes place, so you need to call non-specialized methods.
In fact, the output is as follows (via JAD):
public class MyClass implements ScalaObject { public void foobar(Object obj) { } public void foobar$mcI$sp(int t) { foobar(BoxesRunTime.boxToInteger(t)); } public MyClass() { } } public class MyClass$mcI$sp extends MyClass { public void foobar(int t) { foobar$mcI$sp(t); } public void foobar$mcI$sp(int i) { } public volatile void foobar(Object t) { foobar(BoxesRunTime.unboxToInt(t)); } public MyClass$mcI$sp() {} }
Thus, the problem of erasing your type will not be fixed with @specialized.
source share