Parametric Polymorphism
What you'll learn: How to write generic, reusable code that works uniformly across all types without compromising type safety.
The Core Idea
Parametric polymorphism lets you define functions or data structures that are parameterized by one or more types. Instead of writing separate code for lists of integers, lists of strings, lists of booleans, and so on, you write one generic list that works with any type at all.
The key word is uniformly: the generic code doesn't inspect or depend on what the actual type is—it treats all type parameters the same way. This ensures type safety because the compiler tracks which specific type you're using and checks that operations remain consistent.
Why It Matters
Without parametric polymorphism, you'd either:
- Write duplicate code for every type (tedious and error-prone), or
- Use a single "universal" type that loses type information (unsafe).
Parametric polymorphism gives you both reusability and safety.
Analogy
Think of a shipping container. It doesn't care whether it holds electronics, clothing, or furniture—it can transport anything. Yet each container still knows exactly what it carries, so you never accidentally unload books when you expected bicycles.
How It Works in Practice
When you define a parametric type or function, you introduce a type variable (often written as T, A, or similar). The compiler then substitutes the concrete type when you use it, ensuring all operations stay type-consistent.
For example, a generic pair could hold two values of any type, but once you specify (Int, String), the type checker enforces that the first element is an integer and the second is a string.
Key Takeaway:
Parametric polymorphism enables writing generic, type-safe code once that works uniformly across all types, maximizing reusability without sacrificing compile-time guarantees.