AlgoViz

Covariance and contravariance

hard 45 min

A Dog is an Animal.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:41

Covariance and contravariance

1:03Reel

Theory

Read or listen first. About 2 min.

What it is

Variance describes how the subtype relation of a generic type follows the subtype relation of its argument. Dog is a subtype of Animal. What about Source<Dog> and Source<Animal>?

Covariant: the relation keeps its direction. Source<Dog> may be used as Source<Animal>. It fits types that only give T. Contravariant: the relation turns round. Sink<Animal> may be used as Sink<Dog>. It fits types that only take T. Invariant: no relation at all. It fits types that do both, such as a list you can change.

There is one idea behind all three: substitution. A type may stand in for another if everything that its user may do still works. This is Liskov substitution, applied to type arguments.

Why it exists

If the rule is too loose, a cat ends up in a list of dogs, and the failure comes later and elsewhere. Java arrays are loose in this way, and every store into an array of objects may need a check because of it.

If the rule is too strict, useful calls are refused: a function that prints animals would not print your dogs, and a comparator for animals would not sort them. You would copy lists only to please the compiler.

API designers decide this for all their callers. One well placed out, in or wildcard makes a library pleasant, and a missing one is felt for years.

A short history

  1. 1981

    John C. Reynolds states the rule for function types: reversed for parameters, kept for results.

  2. 1984

    Luca Cardelli makes it widely known with A semantics of multiple inheritance.

  3. 2004

    Java 5 brings generics with wildcards: variance is chosen at the place of use.

  4. 2010

    C# 4 brings out and in on interfaces and delegates: variance is chosen at the declaration.

  5. 2017

    TypeScript 2.6 adds strictFunctionTypes, which compares function type parameters contravariantly.

  6. 2022

    TypeScript 4.7 adds optional out and in annotations on type parameters.

Words to know

Subtype
A value of it is accepted where the other is asked: Dog below Animal.
Covariant
Same direction. Written out T, +T, ? extends T.
Contravariant
Turned round. Written in T, -T, ? super T.
Invariant
Must match exactly. The default for List<T> in Java, C# and Python checkers.
Bivariant
Both directions are accepted. Convenient and not safe. Method parameters in TypeScript.
Producer
Something you read T from.
Consumer
Something you hand T to.
PECS
Producer extends, consumer super. The Java way to remember it.
Declaration site
The author of the type writes the variance once: C#, Kotlin, Scala.
Use site
The user of the type writes it at each use: Java wildcards.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Dog < Animal. Given

Understand it

Start here

The pet day

At a pet day there is a pen with a gate, a house with a window, and people who wash pets. Each can be mislabelled in one direction and not in the other. Watch what goes in and what comes out.

Who may stand in for whom?
DOGS

The smell

A list of dogs is not a list of animals

Java
List<Dog> dogs = new ArrayList<>();dogs.add(new Dog());// List<Animal> animals = dogs;      does not compile, and this is why:// animals.add(new Cat());           fine for a List<Animal>// Dog d = dogs.get(1);              a cat in a dog variableDog[] array = {new Dog()};Animal[] view = array;               // arrays: allowedview[0] = new Cat();                 // compiles, ArrayStoreException when it runs
If line 3 were allowed, line 4 would be correct for the type that it sees.

One list, two names

Leedogs: List<Dog>+ pull(): Dogthe pen[0] Dog[1] Dog[2] Cat

1/3The owner

Lee calls the pen a list of dogs and will ask it for dogs.

uses

If Max could only look, the second name would be harmless.

How it works

Three kinds, one question

The arrows of Source and Sink

AnimalDog

1/4Given

Dog is an Animal. The arrow means: may be used as.

extends (is a)

The three kinds

KindT appearsDog below Animal givesJavaC#, KotlinPythonScala
CovariantOnly in resultsSource<Dog> below Source<Animal>? extends Animalout Tcovariant=True+T
ContravariantOnly in parametersSink<Animal> below Sink<Dog>? super Dogin Tcontravariant=True-T
InvariantIn bothNothingTTTypeVar("T")T
The word variance in Python 3.12: for class Box[T] a checker finds it on its own.

Find the variance of a type

  • Only reads

    Iterators, sequences, suppliers, futures, results. Think out.

  • Only takes

    Comparators, handlers, printers, predicates, loggers. Think in.

  • Reads and takes

    Lists, arrays, mutable boxes, caches. Exact match, or split the interface.

Functions

Parameters in, results out

A function type has both positions, so it has both rules. Animal to Dog may be used where Dog to Animal is asked: it accepts more than needed and returns something more precise than needed. The reverse fails twice.

Why Animal to Dog may stand in for Dog to Animal

Python
PARENT = {"Dog": "Animal", "Cat": "Animal", "Animal": "Object"}VARIANCE = {"Source": "+", "Sink": "-", "Box": "="}def fits(a, b):    """May a value of type a be used where b is asked?"""    if isinstance(a, str) and isinstance(b, str):        while a != b and a in PARENT:            a = PARENT[a]        return a == b    if isinstance(a, str) or isinstance(b, str) or a[0] != b[0]:        return False    if a[0] == "Fn":                                   # ("Fn", parameter, result)        return fits(b[1], a[1]) and fits(a[2], b[2])   # in is reversed, out is not    sign = VARIANCE[a[0]]    forward, back = fits(a[1], b[1]), fits(b[1], a[1])    return {"+": forward, "-": back, "=": forward and back}[sign]assert fits("Dog", "Animal") and not fits("Animal", "Dog")assert fits(("Source", "Dog"), ("Source", "Animal"))assert fits(("Sink", "Animal"), ("Sink", "Dog"))assert not fits(("Box", "Dog"), ("Box", "Animal"))assert not fits(("Box", "Animal"), ("Box", "Dog"))assert fits(("Fn", "Animal", "Dog"), ("Fn", "Dog", "Animal"))assert not fits(("Fn", "Dog", "Animal"), ("Fn", "Animal", "Dog"))assert fits(("Sink", ("Sink", "Dog")), ("Sink", ("Sink", "Animal")))   # twice reversedprint("all rules hold")
The rules as a program. Each assert is a sentence of this page.
Edit and run it in your browser

Four functions for one job

Asked: Dog to AnimalParameterResultFits?
Dog to AnimalsamesameYes
Animal to AnimalwidersameYes
Dog to DogsamenarrowerYes
Animal to DogwidernarrowerYes
Dog to ObjectsamewiderNo, the user may call eat
Puppy to AnimalnarrowersameNo, the user may give a grown dog
Wider means a supertype. Be generous with what you accept and precise in what you return.

PECS

Producer extends, consumer super

Java lists both read and take, so List<T> is invariant. With a wildcard you promise to use only one half, and get the flexibility of that half.

You want toWriteYou canYou cannot
Read animalsList<? extends Animal>Take an Animal out, pass a List<Dog>Add anything but null: it may be a list of cats
Add dogsList<? super Dog>Add a Dog, pass a List<Animal>Take out more than Object: it may hold cats or plain objects
Do bothList<Dog>Read and add dogsPass any other list
NeitherList<?>Ask for the size, clearAdd, or read more than Object
Java
static void printAnimals(List<? extends Animal> animals) {    for (Animal a : animals) a.eat();    // animals.add(new Dog());       no: it may be a List<Cat>}static void addDogs(List<? super Dog> dogs) {    dogs.add(new Dog());    // Dog d = dogs.get(0);          no: only Object is known    Object first = dogs.get(0);}static void processExactly(List<Dog> dogs) {    dogs.add(new Dog());    Dog d = dogs.get(0);}static <T> void copy(List<? extends T> source, List<? super T> dest) {    for (T item : source) dest.add(item);}static void demo() {    List<Dog> dogs = new ArrayList<>(List.of(new Dog(), new Dog()));  // can grow    List<Animal> zoo = new ArrayList<>();    printAnimals(dogs);    addDogs(zoo);    copy(dogs, zoo);    processExactly(dogs);    // processExactly(zoo);          does not compile}
The three kinds and the copy that uses two of them.

Which wildcard?

TypeScript
class Animal { name = "animal"; eat(): void {} }class Dog extends Animal { bark(): void {} }class Cat extends Animal { meow(): void {} }type AnimalHandler = (animal: Animal) => void;type DogHandler = (dog: Dog) => void;const handleAnimal: AnimalHandler = (a) => a.eat();const handleDog: DogHandler = handleAnimal;            // contravariant parametertype DogFactory = () => Dog;const createDog: DogFactory = () => new Dog();const createAnimal: () => Animal = createDog;          // covariant resultinterface StrictBox<T> { get: () => T; set: (v: T) => void }interface LooseBox<T> { get(): T; set(v: T): void }    // method syntaxdeclare const strictDogs: StrictBox<Dog>;declare const looseDogs: LooseBox<Dog>;// const a: StrictBox<Animal> = strictDogs;            error: invariantconst b: LooseBox<Animal> = looseDogs;                 // accepted: bivariant methodsconst dogs: Dog[] = [new Dog()];const animals: Animal[] = dogs;                        // acceptedanimals.push(new Cat());                               // dogs[1].bark() fails at run timeconst safe: readonly Animal[] = dogs;                  // no push, no problem
TypeScript: function properties are strict, methods are not. The second pair of types is accepted, and it should not be.

A method prints the names of animals. What is its parameter?

BreaksList<Animal>
How
Exact type.
Limit
Nobody with a List<Dog> can call it. They will copy or cast.
Choose when
Only if you add animals to it.
WorksList<? extends Animal>
How
Read only wildcard.
Limit
Still demands a List. A Set or a stream of animals cannot be passed.
Choose when
You need get by index.
StrongIterable<? extends Animal>
How
The smallest producer. In Python Iterable[Animal], in C# IEnumerable<Animal>, both covariant already.
Limit
No size, and in some cases it can be read only once.
Choose when
You loop once.

Languages

What is covariant out of the box?

LanguageCovariantContravariantInvariant
JavaArrays (checked when storing), return types of overridesOnly by ? superAll generics without wildcard
C#IEnumerable<out T>, Func<out R>, arrays (checked when storing)Action<in T>, IComparer<in T>List<T>, all classes and structs
KotlinList<out E> (read only)Comparable<in T>MutableList<E>, Array<T>
ScalaList[+A], results of functionsParameters of functionsArray[A]
Python checkersSequence, Iterable, tuple, results of CallableParameters of Callablelist, set, dict
TypeScriptArrays, properties, resultsFunction type parameters in strict modeFunction property in and out
C++Return types of virtual functions, if pointers or referencesNothing built inAll templates: vector<Dog> and vector<Animal> are unrelated
Rust&T, Vec<T>, in lifetimesfn(T) parameters&mut T, Cell<T>
In C# variance works only for interfaces and delegates, and only with reference types: IEnumerable<int> is not an IEnumerable<object>.

Safe to widen

  • A sequence you only read
  • A supplier
  • The result of a method
  • An immutable list

Not safe to widen

  • A list you add to
  • An array you store into
  • A field that can be set
  • A comparator (it is safe to narrow)

Neighbours

How it fits with other ideas

IdeaConnection
GenericsWhere T comes from, and bounds
Liskov substitutionThe reason for all three rules
Method overridingResults may be narrowed in an override
Interface segregationSplit reader and writer, and each half gets a variance
ImmutabilityWhat cannot change can be covariant
ObserverHandlers are consumers

Summary

The whole topic in one minute.

Ask what can be done with T. If T only comes out, a source of dogs is a source of animals. If T only goes in, a washer of animals is a washer of dogs. If both, the type must match exactly.

Functions follow from this: parameters go in, results come out. So a function may replace another if it accepts at least as much and returns at least as precise a result. PECS is the same sentence for Java collections.

  • Variance answers: may F<Dog> be used as F<Animal>, or the other way round?
  • Only out: covariant. Only in: contravariant. Both: invariant
  • Function parameters are contravariant, results are covariant
  • PECS: producer extends, consumer super, no wildcard in results
  • Covariant arrays in Java and C# need a check at each store
  • TypeScript methods and arrays are looser than is safe
  • Split an interface into a reader and a writer to gain flexibility

Sources