AlgoViz

Covariance and contravariance

hard 45 min

A Dog is an Animal.

Watch lesson4:41

Where it shows up

The same pattern appears across everyday software.

  • Java Comparator

    `Comparator.comparing` takes a `Function<? super T, ? extends U>`: the key function consumes T and produces U.

  • Java Collections

    `Collections.addAll(Collection<? super T> c, T... elements)`: the collection consumes.

  • Java arrays

    The API documentation of ArrayStoreException shows an Object array variable that refers to an array of String.

  • C# and .NET

    `IEnumerable<out T>` is covariant, `Action<in T>` contravariant. The documentation explains both with base and derived classes.

  • Kotlin

    `out` and `in` at the declaration, and type projections at the use. The documentation compares them with Java wildcards.

  • Scala

    `+A` and `-A` on type parameters. Function types are contravariant in the parameter and covariant in the result.

  • TypeScript

    The handbook has a section on function parameter bivariance. `strictFunctionTypes` came in 2.6 and `in`, `out` in 4.7.

  • Rust

    The reference lists the variance of built-in types: `&T` is covariant in T, `&mut T` invariant, `fn(T)` contravariant.

  • mypy

    Its documentation explains why a list of a subtype is refused and advises Sequence for parameters that are only read.

  • C++

    A virtual function may return a pointer or reference to a derived class: covariant return types.