Covariance and Contravariance (computer Science)

Covariance And Contravariance (computer Science)

Within the type system of a programming language, covariance and contravariance refers to the ordering of types from narrower to wider and their interchangeability or equivalence in certain situations (such as parameters, generics, and return types).

  • covariant: converting from narrower (Cats) to wider (Animals).
  • contravariant: converting from wider (Shapes) to narrower (Triangles).
  • invariant: not able to convert.

For example, a type W that may hold one of the values from the set {a,b,c,d} is wider than a type N that may only hold values from the narrower set {a,b}. Hence, a type conversion from W to N, such as in the case of passing a double to a function expecting a float, is a covariant conversion. Similarly, a type conversion from N->W, such as in the case of calling a function returning a float in the place of one returning a double, is a contravariant conversion of the function (the function type is its result type).

Note, types may share values yet not be equivalent. For example, types assuming values {a,b} and {b,c}, respectively, are not equivalent to each other...though they are equivalent to a type assuming the values {b} since {b}->{a,b} and {b}->{b,c}.

A class's type equivalence is implied by its inheritance hierarchy (and is the justification for inheritance). However, since all possible changes to a derived class can destroy this assertion, some languages restrict the presumption of this implicit equivalence in some situations.

Read more about Covariance And Contravariance (computer Science):  Formal Definition, Origin of The Terms, Need For Covariant Argument Types?, Avoiding The Need For Covariant Argument Types, Overview of Covariance/contravariance in Some Programming Languages