3 ms·
"parametric polymorphism" is fancy way to say "I'm declaring a type that is composed of other types". The canonical example is a set. In C# (that's what I'm f
by ecoffey 16y ago
"parametric polymorphism" is fancy way to say "I'm declaring a type that is composed of other types".
The canonical example is a set.
In C# (that's what I'm familiar with) we have IEnumerable<T>. It represents enumerating over some homogeneous set of type T.
so when you write "var myList = new List<int>() { 1, 2, 3 };" the type that gets written down in the bytecode is List<int> (which implements IEnumerable<int>).
So the statement "typeof(myList) == typeof(List<int>)" returns true. The type you specified at compile time doesn't loose information at runtime. (For instance you can also do typeof(IEnumerable<>).MakeGenericType(new[] { typeof(int) }), which gets the Generic Type Definition and then you can fill that in at runtime).
The Generics implementation in Java 5 however was all a compiler trick. All the benefits only existed in the AST of the compiler, they never got down to the runtime. So it was easy to check that you couldn't add a int to a strongly typed list of strings, but only in source. (I think, I'm not as well read as javac / JVM internals)
Hopefully that helps.
- jhck 16y agoSo it was easy to check that you couldn't add a int to a strongly typed list of strings, but only in source. (I think, I'm not as well read as javac / JVM internals) You're right. Here's Jim Waldo's explanation from Java: The Good Parts: "the inability to change the VM or bytecodes [due to requirements of backwards compatibility] meant that parameterized types could occur only in the source code. The type system of the runtime hasn’t changed, and doesn’t include generics or parameterized types. What we see in our code as a Set<Player> is seen in the bytecodes as simply a Set of objects."
- ecoffey 16y agoI think read part of that as well, I just don't do Java dev day in, day out is all :-) But this got me thinking about compiler tricks in general, and how they can be a good thing. For instance in C# the keywords foreach, and using are just compiler tricks, as well as the notion of closures.