4 ms·
> If types are not erased then `foo` can behave differently when given, say, a `String` or an `Int` Perhaps worth pointing out that this doesn't apply to langu
by DougBTX 8y ago
> If types are not erased then `foo` can behave differently when given, say, a `String` or an `Int`
Perhaps worth pointing out that this doesn't apply to languages like Java and C# though (which I think is the most common comparison, since generic support is quite similar between the two, but Java has type erasure and C# doesn't) as both languages support `instanceof` and `getClass`, which would allow a function to change its behaviour based on the type of its arguments.
It seems that once the type of an object can be determined at runtime, the argument that it is beneficial to hide the type of a generic parameter is quite a bit weaker.
It also removes some useful features, eg, without type erasure, this is possible:
collection.getFirstValueOfType<Foo>()
including compile-time checks that the collection can contain elements of type Foo.
- noelwelsh 8y agoYeah, it's an interesting design decision in the context of Java. There are certainly lots of Java developers who think erasure is a mistake. I think things like `instanceof` are the mistake, and reifying generics is piling mistakes on top of mistakes, but then I've been hopelessly corrupted by FP. I freely admit this isn't a useful stance to take if one is focused on evolving Java as it currently exists! :-) My above post was mostly about explaining the concept of parametricity, though, and not so much about justifying it.
- DougBTX 8y agoYes, I have to agree about `instanceof` and friends being tricky. Often they seem to come up as a quick fix for some larger architectural problem, resulting in long-term debt. The idea of inferring the set of possible implementations of a function from its signature is neat.
- jdmichal 8y agoI view non-reified types as a mistake in Java, because it's easy to work-around: <T> void doStuff(Class<T> type) There, now you are guaranteed by the compiler to have the type of `T` at runtime. With this simple a work-around, it seems silly that they just didn't properly reify them and call it a day. That being said, it's also such an easy work-around that it's simply annoying at this point when I need to include the extra parameter(s) to get the type.