Generics

Keywords

ver. 1.0.0

Understand and use generics: declaration, JVM erasure and its workarounds, and variance (out/in) with star projections and reified types.

This unit teaches how to declare generic functions, classes and extension properties with type parameters and upper bounds, explains what the JVM erases (and what that prevents), shows how reified inline type parameters recover types at runtime, and develops the concept of variance so you can correctly use out, in, use-site projections and star projections.

You learn to write generic code with confidence: put type parameters on functions, classes and properties, rely on type inference for most calls, and constrain parameters with upper bounds (e.g. <T : Number>). You also learn the important default: an unconstrained T is effectively nullable (Any?) unless you give a non-null upper bound.

The unit explains what the JVM removes: generics are erased at runtime, so List<String> becomes just List. That erasure makes runtime checks like value is List<String> impossible; the idiom List<*> expresses a list of unknown element type when the element argument is irrelevant. To recover type information in code, you use inline functions with reified type parameters — because inlining substitutes the actual type at call sites, is T and T::class become valid in that context.

You also study variance: why List<String> is not automatically a List<Any> even though String is an Any — allowing that would permit unsafe writes. The unit teaches declaration-site variance with out (covariant: produces values) and in (contravariant: consumes values), and contrasts that with use-site projections so you can choose the right approach. Star projections are covered as a safe way to handle unknown but irrelevant type arguments.

By the end you will be able to declare and constrain generic types, reason about what type erasure prevents and when to use List<*> or reified inline functions, and apply out/in and projections correctly so your APIs are type-safe and expressive. The material sets you up to proceed to annotations and reflection, where runtime inspection interacts with erasure and reification.

Materials

Source document

  • Kotlin in Action, Second Edition, Sebastian Aigner, Roman Elizarov, Svetlana Isakova, and Dmitry Jemerov, Manning, April 2024 — Link — Page 252-288