Content deleted Content added
Add in-line citation and information |
|||
Line 1:
{{Short description|Programming language concept}}
{{Type systems}}
Many [[programming language]] [[type system]]s support [[subtyping]]. For instance, if the [[type (computer science)|type]] {{C sharp|Cat}} is a subtype of {{C sharp|Animal}}, then an [[expression (computer science)|expression]] of type {{C sharp|Cat}} [[Liskov_substitution_principle|should be substitutable]] wherever an expression of type {{C sharp|Animal}} is used.
'''Variance'''
Depending on the variance of the [[type constructor]], the subtyping relation of the simple types may be either preserved, reversed, or ignored for the respective complex types. In the [[OCaml]] programming language, for example, "list of Cat" is a subtype of "list of Animal" because the list type constructor is '''covariant'''. This means that the subtyping relation of the simple types
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 (computer science)|parameter]] type. Here, the subtyping relation of the simple types is reversed for the complex types.
In other words, covariance is the quality of being different by being more specific ({{C sharp|Cat}} is covariant to {{C sharp|Animal}}) while 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
In order to keep the type system simple and allow useful programs, a language may treat a type constructor as invariant even if it would be safe to consider it variant, or treat it as covariant even though that could violate type safety.
|