Stumbled over that
def foo(f: Int => Unit) {}
def foo(f: Long => Unit) {}
doesn’t compile because of method foo is defined twice. I know that above is only a shorthand for
def foo(f: Function1[Int, Unit]) {}
def foo(f: Function1[Long, Unit]) {}
and that after type erasure both methods have same signature.
Now I’ve read in Try out specialized Function1/Function2 in 2.8.0 RC1! that Function1 and Function2 have @specialized versions for Int, Long and Double since Scala 2.8. That surely means that Function[Int, Unit] and Function[Long, Unit] have separate class files at JVM level.
Would then not both signatures are different?
Is the problem, that second type parameter will continue to be erased? But same problem with
class Bar[@specialized T]
def foo(f: Bar[Int]) {}
def foo(f: Bar[Long]) {}
it doesn’t compile.
@specialized has nothing to do with type erasure, at least in this case. It means that an extra version of your class is generated with the native type in the position. This saves on boxing/unboxing notably.
So you define a class like:
and you get two classes as output, (approximately):
You need to have two implementations of the class because you can’t always guarantee that the one with the correct native type will be called. The scala compiler will choose which one to call. Note that the java compiler has no idea this specialization is taking place, so must call the unspecialized methods.
In fact, the output is the following (via JAD):
So your type erasure problem will not be fixed with @specialized.