Generics

Subroutines provide a way to provide an operation for a number of different parameter values. Conformant arrays, default parameters, variable number of parameters, e.g., in C int foo(int a, …)`. It often happens that we also need to perform an operation for a number of different parameter types

Polymorphism

In ML, the compiler implements type-safe implicit parametric polymorphism, via structural type equivalence (Hindley-Milner)

Java only allows object types to parameterize generics in their implementation of generics. Ada, C++ allow values of ordinary types, e.g., vector<int>, as well. C# follows Java, and treats ordinary types as special case.

Implementation of generics

In C++, the compiler creates a separate copy of code for each instance. Leads to code bloat.

In Java, all instances share the same code at runtime. Compiler inserts runtime type casts.

C++ templates

  • generic parameters may take values
  • templates may be nested
  • in principle, can do arbitrary computation at compile time
  • Example of template metaprogramming: generic parameter n to sort routing creating routine that sorts array o fsize n with all loops unrolled
  • Expanded then type-checked

Java Type Erasure

  • Replaces all type parameters in generic types with their bounds or Object if the type parameters are unbounded
  • Type casts are inserted to preserve type safety
  • Generates bridge methods to preserve polymorphism in extended generic types
  • C#’s reification replaces the need for type erasure - allows sharing code when necessary
  • JVM not initially created with generics in mind