Handy covariance & contravariance definition, courtesy of this Wikipedia page.

As used in computer science, in particular in object oriented programming:

  • Covariance means that the type of arguments, return values, or exceptions of overriding methods can be subtypes of the original types.
  • Contravariance means that the type of arguments, return values, or exceptions of overriding methods can be supertypes of the original types.

This is contrasted with invariance, where arguments have to be of exactly the same type.

As is usual in the case of object oriented programming, type can be a class and supertype can be any superclass or any implemented protocol or interface.

Covariant parameters are not safe, but covariant return types and exceptions are. Similarly, contravariant parameters are safe, but contravariant return types and exceptions are not. This is because the caller may expect the original type, but in subtyping it doesn’t matter if the overriding method cares less about parameters and cares more about return values and exceptions than expected.