Covariance and contravariance
hard 45 minA Dog is an Animal.
Video lesson · Chapter 1 of 6
Make a prediction
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
1981
John C. Reynolds states the rule for function types: reversed for parameters, kept for results.
1984
Luca Cardelli makes it widely known with A semantics of multiple inheritance.
2004
Java 5 brings generics with wildcards: variance is chosen at the place of use.
2010
C# 4 brings
outandinon interfaces and delegates: variance is chosen at the declaration.2017
TypeScript 2.6 adds
strictFunctionTypes, which compares function type parameters contravariantly.2022
TypeScript 4.7 adds optional
outandinannotations 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.
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.
The smell
A list of dogs is not a list of animals
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 runsOne list, two names
1/3The owner
Lee calls the pen a list of dogs and will ask it for dogs.
uses
How it works
Three kinds, one question
The arrows of Source and Sink
1/4Given
Dog is an Animal. The arrow means: may be used as.
extends (is a)
The three kinds
| Kind | T appears | Dog below Animal gives | Java | C#, Kotlin | Python | Scala |
|---|---|---|---|---|---|---|
| Covariant | Only in results | Source<Dog> below Source<Animal> | ? extends Animal | out T | covariant=True | +T |
| Contravariant | Only in parameters | Sink<Animal> below Sink<Dog> | ? super Dog | in T | contravariant=True | -T |
| Invariant | In both | Nothing | T | T | TypeVar("T") | T |
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
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")Four functions for one job
| Asked: Dog to Animal | Parameter | Result | Fits? |
|---|---|---|---|
Dog to Animal | same | same | Yes |
Animal to Animal | wider | same | Yes |
Dog to Dog | same | narrower | Yes |
Animal to Dog | wider | narrower | Yes |
Dog to Object | same | wider | No, the user may call eat |
Puppy to Animal | narrower | same | No, the user may give a grown dog |
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 to | Write | You can | You cannot |
|---|---|---|---|
| Read animals | List<? extends Animal> | Take an Animal out, pass a List<Dog> | Add anything but null: it may be a list of cats |
| Add dogs | List<? super Dog> | Add a Dog, pass a List<Animal> | Take out more than Object: it may hold cats or plain objects |
| Do both | List<Dog> | Read and add dogs | Pass any other list |
| Neither | List<?> | Ask for the size, clear | Add, or read more than Object |
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}Which wildcard?
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 problemA 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?
| Language | Covariant | Contravariant | Invariant |
|---|---|---|---|
| Java | Arrays (checked when storing), return types of overrides | Only by ? super | All 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 |
| Kotlin | List<out E> (read only) | Comparable<in T> | MutableList<E>, Array<T> |
| Scala | List[+A], results of functions | Parameters of functions | Array[A] |
| Python checkers | Sequence, Iterable, tuple, results of Callable | Parameters of Callable | list, set, dict |
| TypeScript | Arrays, properties, results | Function type parameters in strict mode | Function property in and out |
| C++ | Return types of virtual functions, if pointers or references | Nothing built in | All templates: vector<Dog> and vector<Animal> are unrelated |
| Rust | &T, Vec<T>, in lifetimes | fn(T) parameters | &mut T, Cell<T> |
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
| Idea | Connection |
|---|---|
| Generics | Where T comes from, and bounds |
| Liskov substitution | The reason for all three rules |
| Method overriding | Results may be narrowed in an override |
| Interface segregation | Split reader and writer, and each half gets a variance |
| Immutability | What cannot change can be covariant |
| Observer | Handlers 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 asF<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
- Java language specification, chapter 10: arrays
- Oracle tutorial: Guidelines for wildcard use
- Java API: Comparator
- Java API: ArrayStoreException
- .NET: Covariance and contravariance in generics
- Kotlin: Generics
- Scala: Variances
- TypeScript: Type compatibility
- TypeScript 4.7: variance annotations
- TypeScript 2.6: strict function types
- Rust reference: Subtyping and variance
- mypy: Generics
- Wikipedia: Covariance and contravariance