Covariance and contravariance (computer science): Difference between revisions

Content deleted Content added
Adds concise definition
top: Move latest addition to the correct spot.
Line 1:
{{Type systems}}
Covariance is the quality of being different by being more specific ({{C sharp|Cat}} is covariant to {{C sharp|Animal}}). Contravariance is the quality of being different by being more general ({{C sharp|Animal}} is contravariant to {{C sharp|Cat}}).
 
Many [[programming language]] [[type system]]s support [[subtyping]]. For instance, if the type {{C sharp|Cat}} is a subtype of {{C sharp|Animal}}, then an expression of type {{C sharp|Cat}} [[Liskov_substitution_principle|should be substitutable]] wherever an expression of type {{C sharp|Animal}} is used.
 
Line 9 ⟶ 7:
 
On the other hand, "function from Animal to String" is a subtype of "function from Cat to String" because the function type constructor is '''contravariant''' in the parameter type. Here, the subtyping relation of the simple types is reversed for the complex types.
 
CovarianceIn other words, covariance is the quality of being different by being more specific ({{C sharp|Cat}} is covariant to {{C sharp|Animal}}). Contravariancewhile contravariance is the quality of being different by being more general ({{C sharp|Animal}} is contravariant to {{C sharp|Cat}}).
 
A programming language designer will consider variance when devising typing rules for language features such as arrays, inheritance, and [[generic datatype]]s. By making type constructors covariant or contravariant instead of invariant, more programs will be accepted as well-typed. On the other hand, programmers often find contravariance unintuitive, and accurately tracking variance to avoid runtime type errors can lead to complex typing rules.