Covariance and contravariance (computer science)
From Wikipedia, the free encyclopedia
A covariant type operator in a type system preserves the ordering of types. A contravariant operator reverses . If none of these apply, the operator is invariant. These terms come from category theory (mathematics).
Typical examples:
- the array type is usually covariant on the base type: as StringObject then ArrayOf(String)ArrayOf(Object).
- A function with parameter T defined as fun f(T x):Integer can be replaced by a fun g(S x):Integer - we keep the type of the result fixed for the sake of this example - if TS; this is, if g care less for the type of the parameter it can replace f everywhere as it also returns an Integer. So, in a language accepting function arguments, gf and the type of the parameter for f is said to be contravariant.
- In the general case, the type of the result is covariant.
In Object Oriented Programming, substitution is also implicitly invoked by overriding methods in subclasses: the new method can be used where the old method was invoked in the original code. What is licit overriding and what's not, and the variance of the types involved depends heavily on the programming language.
Contents |
[edit] Origin of the terms
The origin of these terms comes from category theory. Here we see the types in the type system as forming a category C, with arrows representing the subtype relationship. The subtype relationship suposedly reflects the substitution principle: that any expression of type t can be substituted by an expression of type s if st.
Defining a function that accepts type p and returns type r creates a new type in the type system which the new method name is associated with. This function definition operator is actually a functor that creates the type as just said. From the substitution principle above, this functor must be contravariant in the first argument and covariant in the second (see Luca Cardelli).
[edit] The controversy in Object Oriented languages
The problem arises as different object oriented languages have different strategies to select the actual code used in a particular contexts and the first parameter is the object itself (which is not contravariant).
However, it is was shown by Castagna (1995) that all depends on the method fetching algorithm: types used to select the method are contravariant; types not used to select the method are covariant. It's immaterial if the fetching occurs at run-time or at compile time.
These terms are also used in the context of modern programming languages that offer other functors to create new types with type variables, as in generic programming or parametric polymorphism, and exception handling where method definitions are enriched with annotations that indicate possible failures.
[edit] Overview of covariance/contravariance in some programming languages
How types are built from basic types, thus defining the sub-type relationship, and how new methods are defined and override or not existing methods depends on the language and sometimes not necesarily follow the substitution principle above adding runtime checking instead.
Here a simple comparison of how overriding methods behave in some programming languages.
[edit] C++
C++ supports covariant return types in overridden virtual functions.
[edit] C#
Arrays of reference-types are covariant: string[] is a subtype of object[], although with some caveats:
// A is a single-element array of System.String. string[] a = new string[1]; // B is an array of System.Object object[] b = a; // Assign an boxed System.Integer to b. This would be possible if b really were // an array of System.Object, but since it really is an array of System.String, // we will get an System.ArrayTypeMismatchException with the folowing message: // "Attempted to store an element of the incorrect type into the array". b[0] = 1;
Note: In the above case you can read from b without problem. It is only when trying to write to the array that you must know it's real type.
Arrays of value-types are invariant: int[] is not a subtype of double[].
In the C# programming language, support for both return-type covariance and parameter contravariance for delegates was added in version 2.0 of the language. Neither covariance nor contravariance are supported for method overriding.
[edit] Eiffel
Eiffel allows covariant return and parameter types in overriding methods. This is possible because Eiffel does not require subclasses to be substitutable for superclasses — that is, subclasses are not necessarily subtypes.
However, this can lead to surprises if subclasses with such covariant parameter types are operated upon as though they were a more general class (polymorphism), leading to the possibility of compiler errors.
[edit] Java
Arrays of objects are covariant: String[] is a subtype of Object[], although with some caveats:
// A is a single-element array of String. String[] a = new String[1]; // B is an array of Object Object[] b = a; // Assign an Integer to b. This would be possible if b really were // an array of Object, but since it really is an array of String, // we will get an java.lang.ArrayStoreException. b[0] = new Integer (1);
Note: In the above case you can read from b without problem. It is only when trying to write to the array that you must know it's real type.
Arrays of primitive types are invariant: int[] is not a subtype of double[].
Exception covariance has been supported since the introduction of the language. Return type covariance is implemented in the Java programming language version J2SE 5.0. Parameter types have to be exactly the same (invariant) for method overriding, otherwise the method is overloaded with a parallel definition instead.
[edit] REALbasic
REALbasic added support for return type covariance in version 5.5. As with Java, the parameter types of the overriding method must be the same.
[edit] Scala
Scala supports both covariance and contravariance.
[edit] Sather
Sather supports both covariance and contravariance.
[edit] See also
[edit] External links
- Covariance and contravariance: conflict without a cause by G. Castagna
- Contra Vs Co Variance (note this article is not updated about C++)
- Closures for the Java Programming Language (v0.3)