liveBook · Manning

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.

How 2 Manning books explain it

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.

Read how Kotlin in Action, 2E explains contravariance →

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

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.