Contravariance [Was Re: what is easier to learn first?...]

Johann Hibschman johann at physics.berkeley.edu
Wed Mar 22 08:50:44 CET 2000


D Michael McFarland writes:

> I hate to reveal my ignorance to this group (again), but I have to
> ask: What do these terms mean in this context?

Nah, don't worry.  I'm equally ignorant, but I've programmed in
Sather.  ;-)

The issue is how the signature of methods of subclasses are allowed to
differ from those of the superclass.  Contravariance is strict.
Methods in subtypes are allowed to take as arguments the same object
or superclasses, and must return the same object or subclasses.  The
arguments and return type vary oppositely, so it's contravariant.

That made no sense, so here's an example.  A bit abstract, but it's
too late for me to come up with a real-life one.  Say you had a class
A, which has the method

  B foo(C)

i.e. it takes class C as an argument and returns class B.

Under contravariance, a subclass of A, call it A', could implement

  D foo(E)

provided that D was either the same as or a subclass of B, and that E
was either the same as or a superclass of C.  The basic idea is that
the new foo has to be able to handle anything that the old foo could
handle, and return something that code using the old foo could handle.
That way, you can simply substitute class A' for class A without
having any problems.

Covariance lets you *narrow* the allowed argument domain.  So E would
have to be either the same as or a subclass of C.  I think D is under
the same rules, so the transform in the same way and are "covariant".

The standard example here is that Animals eat Food, but Carnivores
only eat Meat, so you want to be able to reduce the scope of the eat()
method for the carnivore subclass of animals.

That's rather rambling, but I hope it conveys the idea.  One of the
more CS-wise folks can probably do a better job.

--Johann


-- 
Johann Hibschman                           johann at physics.berkeley.edu



More information about the Python-list mailing list