BE·36
Generics and Type Parameters
Writing code once for many types. Covers generic classes and methods, bounds, wildcards and PECS, type erasure and its consequences, reifiable types, and variance from first principles. Compared with the four main implementation strategies, erasure (Java, Kotlin, TypeScript), reification (C#), monomorphisation (C++, Rust, Zig) and dictionary passing (Go, Haskell), plus higher-kinded types.
Start here: code that works for any type
The problem generics solve
Before Java 5, a List held plain Objects. You could put anything in, and every read needed a cast that might fail at run time: put an Integer into a list of names by mistake and the program crashed later, somewhere else, when a reader cast it to String. Generics let you write a class or method once with a type parameter (T), and have the compiler fill in and check the real type at each use. List<String> means "a list whose elements are strings", and the compiler refuses to add anything else and removes the need for casts.
A generic class and a generic method
record Result<T>(T value, String error) {
static <T> Result<T> ok(T v) { return new Result<>(v, null); }
static <T> Result<T> fail(String e) { return new Result<>(null, e); }
boolean isOk() { return error == null; }
<R> Result<R> map(Function<T, R> f) { return isOk() ? ok(f.apply(value)) : fail(error); }
}
Result<Integer> price = Result.ok(9000);
Result<String> label = price.map(p -> "₹" + p / 100);
Result<String> missing = Result.<Integer>fail("dish not found").map(p -> "₹" + p / 100);
map over ok: ₹90 | map over failure: dish not found
Result<T> is written once and works for results of any type. <R> Result<R> map(...) is a generic method: it introduces its own type parameter R, so mapping a Result<Integer> with a function from Integer to String gives a Result<String>, all checked by the compiler. Usually Java infers the type arguments (Result.ok(9000) is a Result<Integer>); occasionally you write them explicitly, as in Result.<Integer>fail(...). The <> "diamond" in new Result<>(...) asks the compiler to infer them too.
Bounds: asking for abilities
A plain T could be anything, so you can only call Object's methods on it. A bound asks for more:
static <T extends Comparable<T>> T max(List<T> xs) {
T best = xs.get(0);
for (T x : xs) if (x.compareTo(best) > 0) best = x;
return best;
}
max of ints: 120 | max of strings: vada
T extends Comparable<T> means "any type that can compare itself with its own kind", so compareTo is allowed, and the method works for integers, strings, dates, or your own types that implement Comparable. (extends is used for interfaces too in this position.)
Wildcards: reading and writing
Here's the surprise that trips up everyone: a List<Integer> is not a List<Number>, even though an Integer is a Number. If it were, you could pass it to code that adds a Double, and your list of integers would contain a double. So Java's generics are invariant, and wildcards relax this safely:
static double total(List<? extends Number> xs) { … reads Numbers … } // accepts List<Integer>, List<Double>
static void addDefaults(List<? super Integer> out) { out.add(0); out.add(100); } // accepts List<Integer>, List<Number>, List<Object>
total of List<Integer>: 6.0 | of List<Double>: 4.0
addDefaults into a List<Number>: [0, 100]
The rule is PECS: producer extends, consumer super. If a method only reads Ts out of the collection, accept ? extends T; if it only writes Ts into it, accept ? super T. Collections.copy(List<? super T> dest, List<? extends T> src) uses both.
Erasure: generics vanish at run time
Java implements generics by erasure: the compiler checks the types, then removes them, so at run time a List<String> and a List<Integer> are the same class. That kept old code and libraries working in 2004, and it has consequences you'll meet daily:
List raw = new ArrayList<String>(); // a "raw type": generics switched off
raw.add(42); // only a compiler warning
List<String> names = raw;
String s = names.get(0); // ClassCastException here, far from the bug
raw type let an Integer into a List<String>: ClassCastException far from where it went in
at run time List<String> and List<Integer> are the same class: true
So: never use raw types, treat unchecked warnings as errors, and know that you can't write new T(), instanceof List<String> or overload two methods that differ only in type arguments (the lab shows the compiler errors). Frameworks like Jackson and Spring that need the full type at run time use type tokens to recover it. C# keeps generic types at run time; C++ and Rust generate a separate copy of the code for each type (monomorphisation); Go mixes both; the full-depth sections compare them.
How deep to go in generics
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Use generic collections and APIs; read signatures with T and ? |
| L2 | Write generic classes and methods with bounds; apply PECS |
| L3 | Explain variance, erasure, bridge methods, type tokens, and how C#, C++, Rust, Go and Haskell implement generics |
| L4 | Diagnose heap pollution, unchecked casts, inference failures and erasure clashes |
| L5 | Design generic library APIs that stay usable (inference-friendly, minimal wildcards in return types) |
| L6 | Evolve generic APIs across versions without breaking source or binary compatibility |
Why generics exist
The problem
Before Java 5 (2004), collections held Object:
List names = new ArrayList(); // raw type
names.add("ada");
names.add(42); // compiles: anything is an Object
String s = (String) names.get(1); // ClassCastException at RUN time, far from the bug
Generics (parametric polymorphism) let you write a type or function once with type parameters, and have the compiler check each use:
List<String> names = new ArrayList<>(); // diamond operator infers <String>
names.add("ada");
// names.add(42); // compile error
String s = names.get(0); // no cast
The idea goes back to ML (1973) and CLU. Every statically typed language now has some form of it, but they implement it in very different ways, and the implementation leaks into what you can and can't do.
Four implementation strategies
| Strategy | How it works | Languages | Consequences |
|---|---|---|---|
| Erasure | Type-check with parameters, then erase them to their bounds (Object) in the compiled code. One copy of the code; casts inserted |
Java, Kotlin (JVM), Scala (JVM), TypeScript (types vanish entirely in JS) | Small code, backward compatible with pre-generic bytecode. But there's no T at run time: no new T(), no instanceof List<String>, and boxing for primitives |
| Reification | The runtime knows the actual type arguments; the JIT shares code for reference types and specialises it for value types | C#/.NET | typeof(T) and new T() work, List<int> stores unboxed ints, and is List<string> works |
| Monomorphisation | The compiler generates a separate copy of the code for each concrete type used | C++ templates, Rust, Zig (comptime), D, Swift (specialised when possible) |
Zero-cost abstraction, fully inlinable, no boxing. Costs larger binaries and longer compile times |
| Dictionary passing / GC-shape stenciling | One copy per "shape" plus a hidden runtime dictionary describing the type | Go (since 1.18), Haskell (type-class dictionaries), Swift (unspecialised witness tables) | A compromise between code size and speed. Go instantiates per GC shape (all pointer types share one copy) |
Generic types and methods
Generic classes
A type parameter is a placeholder (T, K, V, E) declared on a class, interface, record, or method:
public final class Page<T> {
private final List<T> items;
private final long total;
private final int page, size;
public Page(List<T> items, long total, int page, int size) {
this.items = List.copyOf(items); this.total = total; this.page = page; this.size = size;
}
public List<T> items() { return items; }
public <R> Page<R> map(Function<? super T, ? extends R> f) { // generic method on a generic type
return new Page<>(items.stream().<R>map(f).toList(), total, page, size);
}
}
// Or as a record:
public record Result<T, E>(T value, E error) {}
pub struct Page<T> {
items: Vec<T>,
total: u64,
page: u32,
size: u32,
}
impl<T> Page<T> {
pub fn map<R>(self, f: impl FnMut(T) -> R) -> Page<R> { // consumes self, no copying of items
Page { items: self.items.into_iter().map(f).collect(), total: self.total, page: self.page, size: self.size }
}
}
type Page[T any] struct {
Items []T
Total int64
Page int
Size int
}
// Go has no generic METHODS with their own type parameters. Map must be a top-level function.
func MapPage[T, R any](p Page[T], f func(T) R) Page[R] {
out := make([]R, len(p.Items))
for i, it := range p.Items {
out[i] = f(it)
}
return Page[R]{Items: out, Total: p.Total, Page: p.Page, Size: p.Size}
}
public sealed record Page<T>(IReadOnlyList<T> Items, long Total, int PageNo, int Size)
{
public Page<R> Map<R>(Func<T, R> f) => new(Items.Select(f).ToList(), Total, PageNo, Size);
}
template <typename T>
struct Page {
std::vector<T> items;
long total; int page, size;
template <typename F>
auto map(F f) const -> Page<std::invoke_result_t<F, const T&>> {
Page<std::invoke_result_t<F, const T&>> out{{}, total, page, size};
out.items.reserve(items.size());
for (const auto& it : items) out.items.push_back(f(it));
return out;
}
};
// Zig: a generic type is a FUNCTION that returns a type at compile time
fn Page(comptime T: type) type {
return struct {
items: []const T,
total: u64,
page: u32,
size: u32,
const Self = @This();
pub fn len(self: Self) usize { return self.items.len; }
};
}
const OrdersPage = Page(Order); // instantiated at compile time
interface Page<T> {
items: readonly T[];
total: number;
page: number;
size: number;
}
const mapPage = <T, R>(p: Page<T>, f: (t: T) => R): Page<R> => ({ ...p, items: p.items.map(f) });
data Page a = Page { items :: [a], total :: Int, page :: Int, size :: Int }
instance Functor Page where -- 'map over the contents' as a type-class instance
fmap f p = p { items = map f (items p) }
Zig shows the idea most plainly: a generic type is a function from types to types, evaluated at compile time. C++ templates and Rust generics do the same thing with special syntax. Haskell makes it explicit too: Page has kind * -> * (it takes a type and returns a type).
Generic methods and type inference
A generic method declares its own type parameters before the return type:
public static <T extends Comparable<? super T>> T max(Collection<? extends T> xs) {
Iterator<? extends T> it = xs.iterator();
T best = it.next();
while (it.hasNext()) { T x = it.next(); if (x.compareTo(best) > 0) best = x; }
return best;
}
// Type arguments are inferred from the arguments and the target type:
LocalDate latest = max(dates);
List<String> empty = Collections.emptyList(); // inferred from the assignment target
var x = Collections.<String>emptyList(); // explicit type witness, rarely needed
Java's inference is local (per expression, using the target type). Rust, Haskell, OCaml, Kotlin and Scala infer more aggressively, and Haskell and OCaml use Hindley–Milner inference that can type whole programs with no annotations. Go infers type arguments from function arguments, but not from return-type context (improved in 1.21).
Constraining type parameters
Bounds
Unbounded T only allows Object operations. Bounds say what a type must support, so the generic code can call those operations:
// Upper bound: T must be a Number (or subtype)
static <T extends Number> double sum(List<T> xs) {
double s = 0; for (T x : xs) s += x.doubleValue(); return s;
}
// Multiple bounds: at most one class, first, then interfaces
static <T extends Entity & Comparable<T> & Serializable> void archive(List<T> xs) { … }
// Recursive bound: "T is comparable to itself" (F-bounded polymorphism)
static <T extends Comparable<T>> void sortInPlace(List<T> xs) { … }
public abstract class Enum<E extends Enum<E>> implements Comparable<E> { … } // the JDK's own
// Trait bounds: inline, or in a where clause
fn sum<T: Copy + std::iter::Sum<T>>(xs: &[T]) -> T { xs.iter().copied().sum() }
fn archive<T>(xs: &[T]) -> Result<(), Error>
where
T: Entity + Ord + serde::Serialize,
{ Ok(()) }
// impl Trait in argument position is sugar for an anonymous type parameter
fn print_all(xs: impl IntoIterator<Item = impl std::fmt::Display>) {
for x in xs { println!("{x}"); }
}
// Constraints are interfaces, which may contain TYPE SETS (union of types)
type Number interface {
~int | ~int32 | ~int64 | ~float32 | ~float64 // ~ includes defined types with that underlying type
}
func Sum[T Number](xs []T) T {
var s T
for _, x := range xs {
s += x // allowed: every type in the set supports +
}
return s
}
// Built-in constraints: any, comparable; package cmp has cmp.Ordered
func Max[T cmp.Ordered](a, b T) T { if a > b { return a }; return b }
// C++20 concepts: named, composable compile-time predicates
template <typename T>
concept Number = std::integral<T> || std::floating_point<T>;
template <Number T>
T sum(std::span<const T> xs) { return std::accumulate(xs.begin(), xs.end(), T{}); }
// Before concepts: unconstrained templates that failed deep inside with pages of errors,
// or SFINAE tricks (std::enable_if) to remove overloads.
// Zig: no declared constraints. comptime checks run during instantiation.
fn sum(comptime T: type, xs: []const T) T {
comptime {
const info = @typeInfo(T);
if (info != .int and info != .float) @compileError("sum needs a numeric type, got " ++ @typeName(T));
}
var s: T = 0;
for (xs) |x| s += x;
return s;
}
// C#: where clauses, including constructor and struct/class constraints, and static abstract members (generic math)
static T Sum<T>(IEnumerable<T> xs) where T : INumber<T>
{
var s = T.Zero;
foreach (var x in xs) s += x; // operators via static abstract interface members (C# 11)
return s;
}
static T Create<T>() where T : new() => new T(); // possible because generics are reified
-- Type-class constraints before =>
sumAll :: Num a => [a] -> a
sumAll = foldr (+) 0
archive :: (Entity a, Ord a, ToJSON a) => [a] -> IO ()
Notice that Java can't abstract over arithmetic: there's no interface for "supports +" on primitives, and generics can't take primitives anyway. C# (generic math via static abstract interface members), Rust (std::ops::Add), Go (type sets), C++ and Zig (templates/comptime) and Haskell (Num) can. Java's answer will come with Valhalla (value classes and, later, specialised generics over primitives).
Associated types
Sometimes a type parameter is determined by another type rather than chosen by the caller. An iterator over a Vec<String> yields String, and nobody should choose otherwise. Rust and Swift express this with associated types:
trait Repository {
type Id; // each implementation fixes its own Id type
type Entity;
fn find(&self, id: &Self::Id) -> Option<Self::Entity>;
}
impl Repository for OrderRepo {
type Id = OrderId;
type Entity = Order;
fn find(&self, id: &OrderId) -> Option<Order> { None }
}
// Iterator is the classic case: trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; }
In Java you'd write interface Repository<E, ID> with two ordinary type parameters. That works, but every use site that's generic over repositories must carry both parameters around (<R extends Repository<E, ID>, E, ID>), even though E and ID are fully determined by R. Spring Data's CrudRepository<T, ID> is this pattern.
Variance
Variance from first principles
If Cat is a subtype of Animal, what's the relationship between Box<Cat> and Box<Animal>? There are three possibilities:
- Covariant:
Box<Cat>is a subtype ofBox<Animal>(same direction). Safe when the box is read-only (a producer): anything you read from aBox<Cat>is anAnimal. - Contravariant:
Box<Animal>is a subtype ofBox<Cat>(reversed). Safe when the box is write-only (a consumer): anything that accepts anyAnimalcan accept aCat. - Invariant: no relationship. Required when the box is read-write.
Why mutable containers must be invariant:
List<Cat> cats = new ArrayList<>();
List<Animal> animals = cats; // suppose this were allowed (covariance)…
animals.add(new Dog()); // …then a Dog gets into a List<Cat>
Cat c = cats.get(0); // ClassCastException: heap pollution
// So Java generics are INVARIANT: List<Cat> is not a List<Animal>. This line doesn't compile.
Java arrays are covariant (a 1995 design decision made so that Arrays.sort(Object[]) could work before generics existed). The hole is plugged with a run-time check: ArrayStoreException (chapter 33).
Function types are the canonical example of both directions: a function Animal → Cat can be used where Cat → Animal is expected. It's contravariant in its parameter (it accepts more) and covariant in its result (it returns something more specific). Every sound type system follows this rule.
Use-site variance: wildcards
Java expresses variance at the use site, each time you mention the type, with wildcards:
| Wildcard | Meaning | You can | You can't |
|---|---|---|---|
List<? extends Animal> |
A list of some subtype of Animal (covariant view) | Read as Animal |
Add anything (except null): you don't know the exact element type |
List<? super Cat> |
A list of some supertype of Cat (contravariant view) | Add Cats (and subtypes) |
Read anything more specific than Object |
List<?> |
A list of some unknown type | Read as Object, size(), clear() |
Add (except null) |
PECS
Joshua Bloch's mnemonic: Producer extends, Consumer super.
// From java.util.Collections: copy from a producer (src) into a consumer (dest)
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
for (int i = 0; i < src.size(); i++) dest.set(i, src.get(i));
}
List<Number> nums = new ArrayList<>(List.of(0, 0, 0));
List<Integer> ints = List.of(1, 2, 3);
Collections.copy(nums, ints); // T = Integer: dest is List<? super Integer>, src is List<? extends Integer>
// Comparators are consumers of T: accept Comparator<? super T>
static <T> void sortBy(List<T> xs, Comparator<? super T> c) { xs.sort(c); }
sortBy(cats, animalByNameComparator); // a Comparator<Animal> can sort Cats
// Functions consume their input and produce their output
<T, R> List<R> mapAll(List<? extends T> xs, Function<? super T, ? extends R> f) { … }
Rules of thumb:
- Use wildcards in parameters of public APIs to make them flexible.
- Don't use wildcards in return types, because they force callers to deal with them.
- If a parameter is both produced and consumed, use an exact
T. ComparableandComparatorare always consumers:<T extends Comparable<? super T>>letsjava.sql.Timestamp-style subclasses that inheritcompareTofrom a parent work.
Wildcard capture: you can't call list.set(0, list.get(0)) on a List<?>, even though it's obviously safe, because the compiler can't name the unknown type. A private generic helper "captures" it:
static void swapFirstTwo(List<?> list) { swapHelper(list); }
private static <T> void swapHelper(List<T> list) { T a = list.get(0); list.set(0, list.get(1)); list.set(1, a); }
Declaration-site variance
Kotlin, Scala, C# and TypeScript (since 4.7) let the type's author declare variance once, at the definition, so users don't need wildcards everywhere:
// out = covariant (T only in output positions); in = contravariant (T only in input positions)
interface Source<out T> { fun next(): T } // Source<Cat> is a Source<Animal>
interface Sink<in T> { fun put(item: T) } // Sink<Animal> is a Sink<Cat>
// Kotlin's read-only List is declared List<out E>, so List<Cat> IS a List<Animal>.
// MutableList<E> is invariant. Use-site projections also exist: MutableList<out Animal>.
fun feedAll(animals: List<Animal>) { }
feedAll(listOf<Cat>()) // OK in Kotlin; the Java equivalent needs List<? extends Animal>
// Scala: +T covariant, -T contravariant
trait Source[+T] { def next(): T }
trait Sink[-T] { def put(t: T): Unit }
// Immutable List[+A] is covariant. Function1[-A, +B] encodes the function variance rule in its declaration.
// C#: out/in on generic interfaces and delegates (not classes)
public interface IProducer<out T> { T Next(); }
public interface IConsumer<in T> { void Put(T item); }
IEnumerable<string> s = new List<string>();
IEnumerable<object> o = s; // OK: IEnumerable<out T>
// List<object> lo = new List<string>(); // error: List<T> is invariant
// Rust infers variance from how a type uses its parameters (no annotations).
// &'a T is covariant in T and in 'a; &'a mut T is INVARIANT in T; fn(T) -> U is contravariant in T.
// Variance in Rust mostly matters for LIFETIMES: &'static str can be used where &'a str is expected.
// PhantomData<T> lets you declare how an unused parameter should behave.
// TypeScript checks variance structurally. Method parameters are (unsoundly) BIVARIANT for compatibility;
// with strictFunctionTypes, function-typed PROPERTIES are checked contravariantly.
interface Producer<out T> { next(): T } // optional explicit variance annotations (TS 4.7)
interface Consumer<in T> { put(t: T): void }
// Arrays are covariant (and unsound) in TS, like Java arrays but without a run-time check.
const cats: Cat[] = [];
const animals: Animal[] = cats;
animals.push(new Dog()); // compiles; cats now contains a Dog
Go has no variance at all: []Cat is not a []Animal, even when Cat implements the interface Animal, because the memory layouts differ (a slice of structs versus a slice of two-word interface values). You must convert element by element.
Erasure and its consequences
Type erasure
Java added generics in Java 5 with a hard constraint: existing bytecode and libraries must keep working (migration compatibility). The solution was erasure:
- The compiler type-checks with full generic information.
- It replaces each type parameter with its erasure: the leftmost bound, or
Object. - It inserts casts where values come out of generic code.
- It generates bridge methods to preserve polymorphism when erased signatures differ.
// You write:
public class Box<T extends Comparable<T>> { private T v; public T get() { return v; } }
String s = new Box<String>().get();
// Roughly compiled to:
public class Box { private Comparable v; public Comparable get() { return v; } }
String s = (String) new Box().get(); // checkcast inserted
// Bridge method example
class Name implements Comparable<Name> {
public int compareTo(Name o) { … }
// compiler-generated bridge so Comparable.compareTo(Object) still dispatches here:
// public int compareTo(Object o) { return compareTo((Name) o); }
}
Generic signatures are kept in class files as metadata (the Signature attribute), which is why reflection can tell you that a field is declared as List<String>. What's erased is the type argument of each object: a new ArrayList<String>() and a new ArrayList<Integer>() are the same class at run time.
Consequences:
// 1. No instanceof or casts with type arguments
if (obj instanceof List<String>) { } // error (List<?> is fine)
// 2. Can't create instances or arrays of T
T t = new T(); // error. Pass a Supplier<T> or Class<T> instead
T[] arr = new T[10]; // error. Use (T[]) new Object[10] with an unchecked warning, or List<T>
// 3. Overloads that erase to the same signature clash
void handle(List<String> xs) {}
void handle(List<Integer> xs) {} // error: name clash, same erasure
// 4. Static members are shared across all parameterisations
class Counter<T> { static int count; } // one count for Counter<String> and Counter<Integer>
// 5. Can't catch or throw generic exception types; no primitives as type arguments
List<int> xs; // error: List<Integer> (boxing)
// 6. Can't implement the same generic interface twice with different arguments
class X implements Comparable<A>, Comparable<B> {} // error
Workarounds that recover type information:
// Type tokens: pass Class<T>
<T> T fromJson(String json, Class<T> type) { return mapper.readValue(json, type); }
// Super type tokens for nested generics: anonymous subclasses keep their generic superclass in metadata
List<Order> orders = mapper.readValue(json, new TypeReference<List<Order>>() {}); // Jackson
ParameterizedTypeReference<List<Order>> ref = new ParameterizedTypeReference<>() {}; // Spring RestClient
Kotlin works around erasure for inline functions with reified type parameters. The function body is inlined at each call site, where the concrete type is known:
inline fun <reified T> ObjectMapper.read(json: String): T = readValue(json, T::class.java)
val order: Order = mapper.read(json) // T known at the call site
inline fun <reified T> Iterable<*>.ofType(): List<T> = filter { it is T }.map { it as T }
Reifiable versus non-reifiable types
A type is reifiable if its full information is available at run time:
- Reifiable: primitives, non-generic types (
String), raw types (List), unbounded wildcard types (List<?>), and arrays of reifiable types. - Non-reifiable:
List<String>,Map<K, V>,T,List<? extends Number>.
This matters for arrays (an array must know its element type at run time to throw ArrayStoreException) and for varargs of generic types, which create arrays:
static <T> List<T> listOf(T... items) { return Arrays.asList(items); }
// warning: "Possible heap pollution from parameterized vararg type T"
@SafeVarargs // the author promises not to store into or expose the varargs array unsafely
static <T> List<T> safeListOf(T... items) { return List.of(items); }
// Heap pollution: a variable of a parameterised type refers to an object not of that type
List<String>[] arr = (List<String>[]) new List<?>[1]; // unchecked
Object[] oa = arr;
oa[0] = List.of(42); // no ArrayStoreException (erased types match)
String s = arr[0].get(0); // ClassCastException later, far away
C# has none of these problems because its generics are reified: typeof(List<string>) != typeof(List<int>), new T[10] works, and List<int> is unboxed. The cost was breaking compatibility: .NET 2.0 introduced a separate set of generic collection types (System.Collections.Generic) beside the old ones.
Monomorphisation, dictionaries and higher kinds
Monomorphisation in Rust, C++ and Zig
When Rust compiles fn largest<T: PartialOrd + Copy>(xs: &[T]) -> T and you call it with &[i32] and &[f64], the compiler emits two functions, largest::<i32> and largest::<f64>, each optimised as if written by hand. Consequences:
- Zero runtime cost: no boxing, no indirection, full inlining and vectorisation. This is why Rust iterator chains and C++ ranges compile to tight loops.
- Code bloat and compile time: each instantiation is compiled separately. Large generic codebases (heavy Serde use, deeply generic async code) see long builds and big binaries. Mitigations: an inner non-generic function (
fn foo<P: AsRef<Path>>(p: P) { inner(p.as_ref()) }),dyn Traitwhere speed doesn't matter, and fewer instantiations. - Errors at instantiation (C++ before concepts, and Zig): errors appear when a template is used with an unsuitable type, sometimes deep inside library code. Rust checks generic bodies against their trait bounds at definition, so errors are local and readable, which is a big ergonomic difference from C++ templates.
- C++ templates are Turing-complete (template metaprogramming,
constexpr, specialisation). Zig'scomptimegives the same power with ordinary Zig code instead of a separate template language.
// Zig: the same function runs at compile time to build types, and at run time on values
fn Matrix(comptime T: type, comptime rows: usize, comptime cols: usize) type {
return struct {
data: [rows][cols]T,
pub fn mul(a: @This(), b: Matrix(T, cols, rows)) Matrix(T, rows, rows) { … } // dimensions checked at compile time
};
}
Go's generics
Go (1.18, 2022) chose a middle path called GC shape stenciling with dictionaries. Types with the same "GC shape" share one compiled instantiation: all pointer types share one, while int and float64 get their own. A hidden dictionary argument carries per-type information such as method addresses. Results:
- Generic code over pointer and interface types can be slower than hand-written code, because method calls go through the dictionary and can't be inlined.
- Generic code over basic value types is usually as fast as hand-written code.
- Language limits: no generic methods (methods can't introduce new type parameters), no specialisation, no variance, and constraints are interfaces with type sets.
Higher-kinded types
Generics abstract over types: List<T> for any T. Higher-kinded types (HKTs) abstract over type constructors: write code once for any container F<_> (List, Optional, Future, Page…). Haskell's Functor and Monad need them:
class Functor f where -- f has kind * -> *: it's a type constructor, not a type
fmap :: (a -> b) -> f a -> f b
instance Functor Maybe where …
instance Functor [] where …
instance Functor Page where … -- one abstraction for every "container"
-- generic code over ANY functor:
double :: (Functor f, Num a) => f a -> f a
double = fmap (* 2)
Java, C#, Go, Rust, Kotlin and TypeScript can't express this directly. You can't write interface Functor<F<_>>. Each container gets its own map (Stream, Optional, CompletableFuture thenApply, Reactor's map) with no shared abstraction. Scala has HKTs (F[_]), enabling libraries like Cats and ZIO. Rust's generic associated types (GATs, stable since 1.65) recover some HKT-like patterns, as do lending iterators. Libraries like Arrow (Kotlin) and Vavr and HKJ (Java) emulate HKTs with type-level encodings, at an ergonomic cost.
Generics paradigm summary
| Java | Kotlin | C# | Go | Rust | C++ | Zig | Haskell | TypeScript | |
|---|---|---|---|---|---|---|---|---|---|
| Implementation | Erasure | Erasure (+ reified inline) |
Reified | Shape stenciling + dictionaries | Monomorphisation | Monomorphisation | Comptime monomorphisation | Dictionaries (specialisation pragmas) | Erased (types don't exist at run time) |
| Primitives as arguments | No (boxing) | No (boxing) | Yes | Yes | Yes | Yes | Yes | Yes (with unboxed types) | n/a |
| Constraints | Bounds (extends, &) |
Bounds, where |
where, static abstract members |
Interfaces with type sets | Trait bounds | Concepts (C++20) | comptime checks | Type classes | extends |
| Variance | Use-site wildcards | Declaration + use-site | Declaration (interfaces, delegates) | None | Inferred | None (templates are unrelated) | None | n/a (no subtyping) | Structural, with optional annotations |
| Checked at definition? | Yes | Yes | Yes | Yes | Yes | No (yes with concepts) | No | Yes | Yes |
| Higher-kinded types | No | No | No | No | Partial (GATs) | Template template parameters | Yes (types are values) | Yes | No |
Lab: where erasure bites, and what generics cost
Java experiments run on JDK 21 (unchecked warnings left visible on purpose); the last experiment uses Go 1.24 to compare three ways of writing generic code.
Experiment 1: covariant arrays versus invariant generics
Object[] arr = new String[1];
arr[0] = 42;
// List<Object> l = new ArrayList<String>(); ← does not compile
Object[] arr = new String[1]; arr[0] = 42 → java.lang.ArrayStoreException: java.lang.Integer
Java arrays are covariant (a String[] is an Object[]), which is unsound, so every array store is checked at run time and fails with ArrayStoreException. Generics were designed later to be invariant, so the same mistake is a compile error. That mismatch is why you can't create a generic array (new T[n], new List<String>[n]): an erased array couldn't perform the run-time check. Prefer List<T> to T[] in generic code.
Experiment 2: an unchecked cast checks nothing
@SuppressWarnings("unchecked") static <T> T unsafeCast(Object o) { return (T) o; }
List<String> names = unsafeCast(List.of(1, 2)); // succeeds
String first = names.get(0); // fails here
unsafeCast(List.of(1,2)) to List<String> succeeded; size 2
...ClassCastException only when reading an element: class java.lang.Integer cannot be cast to class java.lang.String
After erasure, (T) o is a cast to Object: it compiles to nothing. The compiler inserts the real cast (to String) at the use site, so the exception points at an innocent line, possibly in another module and much later. This is heap pollution. Every @SuppressWarnings("unchecked") is a promise you have proved the cast safe; keep them on the smallest possible scope with a comment explaining why.
Experiment 3: catching pollution at the source
List checked = Collections.checkedList(new ArrayList<String>(), String.class);
checked.add(42);
Collections.checkedList rejects at insert: Attempt to insert class java.lang.Integer element into collection with element type class java.lang.String
A checked view carries a Class object and checks every insert, moving the failure to the line with the bug. It's a debugging tool when a polluted collection is reaching your code from legacy or reflective code (deserialisers, old libraries using raw types).
Experiment 4: erasure doesn't erase everything
static List<Map<String, Integer>> field;
abstract class TypeRef<T> { Type type() { return ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } }
new TypeRef<Map<String, List<Integer>>>() {}.type();
new ArrayList<String>() at run time: java.util.ArrayList
field's declared type: java.util.List<java.util.Map<java.lang.String, java.lang.Integer>>
type token: java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>
Objects don't know their type arguments, but declarations do: field types, method signatures and superclass declarations keep full generic types in the class file's Signature attribute. The anonymous subclass new TypeRef<…>() {} declares a superclass with the type argument baked in, which reflection can read. This "super type token" is exactly how Jackson's TypeReference, Spring's ParameterizedTypeReference and Guava's TypeToken deserialise List<Order> correctly, and how Spring injects a Repository<Order> by its type arguments.
Experiment 5: what the compiler forbids
void print(List<String> xs) {}
void print(List<Integer> xs) {}
<T> T make() { return new T(); }
<T> boolean is(Object o) { return o instanceof T; }
Bad.java:4: error: name clash: print(List<Integer>) and print(List<String>) have the same erasure
Bad.java:5: error: unexpected type
Bad.java:6: error: Object cannot be safely cast to T
All three follow from erasure: both print methods become print(List) in bytecode; T doesn't exist at run time to construct or test. The workarounds: distinct method names; pass a Supplier<T> (make(Order::new)) or a Class<T> (type.getDeclaredConstructor().newInstance(), type.isInstance(o)).
Experiment 6: three ways to write generic code, in Go
Summing 10 million integers in Go, with a type-parameterised function, with interface method calls, and with []any plus type assertions:
func SumGeneric[T Number](xs []T) T { var s T; for _, x := range xs { s += x }; return s }
func SumIface(xs []Adder) int { s := 0; for _, x := range xs { s = x.Add(s) }; return s }
func SumAny(xs []any) int { s := 0; for _, x := range xs { s += x.(int) }; return s }
10M ints: generic SumGeneric[int] 9.4ms | interface method calls 50ms | []any with type assertions 25.7ms | equal true
The generic version is about 5× faster than dynamic dispatch through an interface: Go compiles a specialised copy per "GC shape" (all pointer types share one, each value type gets its own), so SumGeneric[int] is a plain loop over a flat []int. The interface and any versions store each value as a separate boxed interface value and pay an indirect call or a type check per element, like Java's List<Integer> (chapter 33's lab). This is the trade-off running through the chapter: erasure (Java) gives one copy of the code and requires boxing; monomorphisation (C++, Rust) gives the fastest code at the cost of compile time and binary size; reified generics (C#) keep types at run time and specialise for value types; Go sits in between.
Try it yourself
- Write
static <T> T[] toArray(List<T> xs)and discover why you need anIntFunction<T[]>parameter (asCollection.toArraydoes). - Compile a class with a generic method and a class that overrides a generic interface method, then run
javap -c -pto find the bridge method the compiler generated. - Port experiment 6 to Rust (a generic
fn sum<T: Add>versus&[Box<dyn Adder>]) and compare the binary sizes with one versus five instantiations. - Use
TypeRefto write a tinydeserialize(String json, TypeRef<T> type)stub that prints which element type it would construct.
Revision sheet: generics
Key ideas
- Generics move type errors from run time to compile time and remove casts: type parameters on classes, interfaces and methods; inference and the diamond.
- Bounds (
T extends Comparable<? super T>, intersection boundsT extends A & B) grant operations onT. - Variance: Java generics are invariant; use-site wildcards (
? extendsto read,? superto write: PECS);?alone for "any". Kotlin and C# use declaration-siteout/in; Scala+T/-T; arrays are covariant and checked at run time. - Erasure: type arguments are removed; casts inserted at use sites; bridge methods preserve overriding; declarations keep generic signatures readable by reflection (type tokens).
- Consequences: no
new T(),new T[],instanceof List<String>, primitives as type arguments (until Valhalla), or overloads differing only by type arguments. - Implementations elsewhere: C# reified generics, specialised for value types; C++ templates and Rust generics monomorphise; Go uses GC-shape stenciling with dictionaries; Haskell type classes and higher-kinded types; TypeScript's structural generics are erased entirely.
Numbers to remember
- Lab: Go's generic sum was about 5× faster than interface dispatch and about 2.7× faster than
[]any.
Pitfalls
- Raw types and ignored unchecked warnings (heap pollution surfacing far away).
@SuppressWarnings("unchecked")on whole classes.- Wildcards in return types (forces callers to deal with them); overly clever bounds that break inference.
- Generic arrays and varargs of generic types (
@SafeVarargsonly when you don't store or expose the array). - Expecting
List<Integer>to be aList<Number>.
Glossary
- Type parameter / argument:
Tin the declaration /Stringat the use. - Invariance / covariance / contravariance: no subtyping between
G<A>andG<B>/ followsA <: B/ reverses it. - Erasure: compiling generics away, leaving bounds (or
Object). - Reification: keeping type arguments at run time.
- Heap pollution: a variable of a parameterised type referring to an object of a different parameterisation.
- Bridge method: a compiler-generated method that keeps overriding working after erasure.