Hacker News new | ask | show | jobs
by kailuowang 3680 days ago
I actually think type erasure might even be the right way to implement generics. You see, the point of static types is to provide compilation time check. That is, types are compilation time concern. So yeah, type erasure did introduce some inconvenience but if you need to access them during runtime, either you did it wrong or the compiler fails at some point.

So, claiming type erasure making generic useless is a false argument.

4 comments

I think that the problem with Java is not that they are implemented with type erasure (many functional languages do the same and monomorphize only when optimizing), the issue is that this implementation detail is a leaky abstraction in Java.
Type erasure also makes some forms of function overloading impossible.

    void func(List<ClassA> list);
    void func(List<ClassB> list);
Using type erasure, I cannot specify functions that are overloaded based on the generic type of an argument. To the runtime, both of these accept an argument of type List<Object>, and so it is ambiguous which one to call.

In C++, which does not use type erasure, this sort of function overloading works as expected.

Not to mention, having type erasure made them backwards compatible with non-generic implementations. I don't think it would have been acceptable to break old Java code or introduce an entirely new collections library like .Net did.
Pretty sure the scope of the generic stage is the compilation unit.