Skip to content
Commitwise
Menu

Variance

The rules for whether a generic type of a subtype counts as a generic type of its supertype.

Definition

If Cat is an Animal, a read-only list of cats can safely be used as a list of animals (covariance), but a writable one can't, or a Dog could be added to it. Kotlin declares variance on types with out and in, Java uses wildcards at each use (? extends to read, ? super to write), and Swift generics are invariant except for the built-in collections.

In practice

Kotlin's List<out E> is covariant, so a List<Cat> can be passed where a List<Animal> is expected, while MutableList<Cat> can't.

Learn it in context

Lessons that use this term.

Related terms

Esc

Type to search the whole site.