Covariance and contravariance (computer science)




The type system of many programming languages supports subtyping. For instance, if Cat
is subtype of Animal
, then an expression of type Cat
can be used whenever an expression of type Animal
could. Variance refers to how subtyping between more complex types (list of Cat
s versus list of Animal
s, function returning Cat
versus function returning Animal
, ...) relates to subtyping between their components. Depending on the variance of the type constructor, the subtyping relation may be either preserved, reversed, or ignored. For example in OCaml, "list of Cat" is a subtype of "list of Animal" because the list constructor is covariant, while "function from Animal to String" is a subtype of "function from Cat to String" because the function type constructor is contravariant in the argument type.