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

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

dogsname of type Dog[]mayread Dogthe penreal type Dog[][0]Rex[1]free

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

AssignmentAttackVerdict
1Source<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

    major

    Nobody with a list of a subtype can call the method.

    Wrong
    def names(animals: list[Animal]): ...
    Right
    def names(animals: Iterable[Animal]): ...
  • Casting the error away

    critical

    The compiler was right. The cat arrives later, in another file.

    Wrong
    List<Animal> a = (List<Animal>) (List<?>) dogs;
    Right
    List<? extends Animal> a = dogs;
  • Wildcard in a result

    major

    Every caller inherits a type that they cannot name.

    Wrong
    List<? extends Order> find();
    Right
    List<Order> find();
  • Narrowing a parameter in an override

    critical

    It is another method. The base method still runs for callers with the base type.

    Wrong
    public boolean equals(Point other)
    Right
    @Overridepublic boolean equals(Object other)
  • Passing a mutable array to a stranger

    major

    TypeScript accepts the wider array type, and push is allowed on it.

    Wrong
    function fill(list: Animal[]) { list.push(new Cat()) }
    Right
    function 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