Contravariance
Contravariance is a type-system relationship in which subtyping between parameterized types reverses the subtyping relationship between their type arguments, typically for input positions.
Kotlin in Action, 2E
A contravariant type parameter is a generic type parameter that reverses the subtype direction of its type arguments and is restricted to in positions.
- How it is used
- Models consumer-style Kotlin APIs so handlers for supertypes can be supplied where handlers for subtypes are required.
- How deep it goes
- Defines reversed generic subtyping through Comparator and function examples, then applies it to star-projected validators and casts.
- Examples
- Uses fruit weight comparators, an Animal extension passed for cats, and a `KClass`-keyed `FieldValidator` registry.
- What you can do after
- Evaluate/understand when an `in`-typed consumer can safely replace a consumer of a narrower type and why star projections reject inputs.
Fabulous Adventures in Data Structures and Algorithms
Contravariance is a type-system relationship in which a more-derived type parameter can substitute for a less-derived type parameter in input positions.
- How it is used
- Explains why input-only generic interfaces support assignment conversions opposite to the underlying type relationship.
- How deep it goes
- Explains input positions, reversed assignments, and categorical morphisms, but treats category theory as only a surface-level introduction.
- Examples
- Uses Animal, Giraffe, and Tiger types with an IC<T> comparison interface and an IC<Animal> to IC<Giraffe> assignment.
- What you can do after
- Evaluate type assignments involving C# contravariant interfaces and explain their reversed compatibility using input positions.
Read how Fabulous Adventures in Data Structures and Algorithms explains contravariance →
Related concepts
- covariancecontrasts with · Covariance is a type-system property in which subtyping of a type argument induces the same-direction subtyping relationship for its parameterized type.
- in positionuses · An in position is a type-parameter usage position in which values of the parameterized type are accepted or consumed rather than produced.
- comparison functionused by · A comparison function or strategy compares two values and indicates their relative ordering, and sometimes whether they are equivalent.
- assignment compatibilityproduces · Assignment compatibility is a type-system relation determining whether a value or expression of one type can be assigned to an object of another type.
- membership operatorconfigured by · A membership operator is a language construct that tests whether a specified value or property is present in a supported collection, range, or object.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.

