Covariance and contravariance
hard 45 minA Dog is an Animal.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Follow one value as it goes in or comes out, and see which type name is safe for the object that holds it.
Operations
One array, two names
A covariant array in the style of Java. The array has to defend itself.
Step 1 of 5
An array of dogs
One cell holds Rex, the other is free.
Step 1: An array of dogs
class Array: def get(self, i): return self.items[i] def set(self, i, value): if not isinstance(value, self.kind): raise ArrayStoreError() self.items[i] = valuedogs = Array(Dog, 2)animals = dogsanimals.set(1, puppy)animals.set(1, cat)- Rule
- Covariant, not safe alone
- Good to know
- A check at each store
- Noticed
- while running
If nobody could store, the second name would be harmless.
In the real world
The same covariance and contravariance doing real jobs. Pick one and step through it.
For each assignment, look for one legal call that goes wrong.
Step 1 of 5
Source, widened
| Assignment | Attack | Verdict | |
|---|---|---|---|
| 1 | Source<Animal> = Source<Dog> | get().eat() | safe |
| 2 | |||
| 3 | |||
| 4 | |||
| 5 | |||
| 6 |
Everything that can be called still works.
Step 1: Source, widened
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Exact type where you only read
majorNobody with a list of a subtype can call the method.
Wrongdef names(animals: list[Animal]): ...Rightdef names(animals: Iterable[Animal]): ...Casting the error away
criticalThe compiler was right. The cat arrives later, in another file.
WrongList<Animal> a = (List<Animal>) (List<?>) dogs;RightList<? extends Animal> a = dogs;Wildcard in a result
majorEvery caller inherits a type that they cannot name.
WrongList<? extends Order> find();RightList<Order> find();Narrowing a parameter in an override
criticalIt is another method. The base method still runs for callers with the base type.
Wrongpublic boolean equals(Point other)Right@Overridepublic boolean equals(Object other)Passing a mutable array to a stranger
majorTypeScript accepts the wider array type, and push is allowed on it.
Wrongfunction fill(list: Animal[]) { list.push(new Cat()) }Rightfunction filled(list: readonly Animal[]): Animal[]
Interview tips
One question
- Where does T appear?
- Only out, only in, or both
- Constructors do not count
PECS
- Producer extends
- Consumer super
- Results: no wildcard
Attack it
- Play the user
- One legal call that breaks
- None found: safe
Design
- Split reader and writer
- Read only views
- One cast behind a typed border