HOME

TheInfoList



OR:

Many
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
type system In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progr ...
s support
subtyping In programming language theory, subtyping (also subtype polymorphism or inclusion polymorphism) is a form of type polymorphism in which a subtype is a datatype that is related to another datatype (the supertype) by some notion of substitutability, ...
. For instance, if the type is a subtype of , then an expression of type should be substitutable wherever an expression of type is used. Variance refers to how subtyping between more complex types relates to subtyping between their components. For example, how should a list of s relate to a list of s? Or how should a function that returns relate to a function that returns ? Depending on the variance of the
type constructor In the area of mathematical logic and computer science known as type theory, a type constructor is a feature of a typed formal language that builds new types from old ones. Basic types are considered to be built using nullary type constructors. S ...
, 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 are preserved for the complex 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 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 ( is covariant to ) while contravariance is the quality of being different by being more general ( is contravariant to ). A programming language designer will consider variance when devising typing rules for language features such as arrays, inheritance, and generic datatypes. 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. 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.


Formal definition

Within the
type system In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progr ...
of a
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
, a typing rule or a type constructor is: * ''covariant'' if it preserves the ordering of types (≤), which orders types from more specific to more generic: If A ≤ B, then I ≤ I; * ''contravariant'' if it reverses this ordering: If A ≤ B, then I ≤ I; * ''bivariant'' if both of these apply (i.e., if A ≤ B, then I ≡ I); * ''variant'' if covariant, contravariant or bivariant; * ''invariant'' or ''nonvariant'' if not variant. The article considers how this applies to some common type constructors.


C# examples

For example, in
C#, if is a subtype of , then: * is a subtype of . The subtyping is preserved because is covariant on . * is a subtype of . The subtyping is reversed because is contravariant on . * Neither nor is a subtype of the other, because is invariant on . The variance of a C# generic interface is declared by placing the (covariant) or (contravariant) attribute on (zero or more of) its type parameters. For each so-marked type parameter, the compiler conclusively verifies, with any violation being fatal, that such use is globally consistent. The above interfaces are declared as , , and . Types with more than one type parameter may specify different variances on each type parameter. For example, the delegate type represents a function with a contravariant input parameter of type and a covariant return value of type . The typing rules for interface variance ensure type safety. For example, an represents a first-class function expecting an argument of type , and a function that can handle any type of animal can always be used instead of one that can only handle cats.


Arrays

Read-only data types (sources) can be covariant; write-only data types (sinks) can be contravariant. Mutable data types which act as both sources and sinks should be invariant. To illustrate this general phenomenon, consider the array type. For the type we can make the type , which is an "array of animals". For the purposes of this example, this array supports both reading and writing elements. We have the option to treat this as either: * covariant: a is an ; * contravariant: an is a ; * invariant: an is not a and a is not an . If we wish to avoid type errors, then only the third choice is safe. Clearly, not every can be treated as if it were a , since a client reading from the array will expect a , but an may contain e.g. a . So the contravariant rule is not safe. Conversely, a cannot be treated as an . It should always be possible to put a into an . With covariant arrays this cannot be guaranteed to be safe, since the backing store might actually be an array of cats. So the covariant rule is also not safe—the array constructor should be ''invariant''. Note that this is only an issue for mutable arrays; the covariant rule is safe for immutable (read-only) arrays. Likewise, the contravariant rule would be safe for write-only arrays. With C# you can play around this by using the dynamic keyword over array/collection/generics with
duck typing Duck typing in computer programming is an application of the duck test—"If it walks like a duck and it quacks like a duck, then it must be a duck"—to determine whether an object can be used for a particular purpose. With nominative ty ...
, the intellisense is lost this way but it works.


Covariant arrays in Java and C#

Early versions of Java and C# did not include generics, also termed
parametric polymorphism In programming languages and type theory, parametric polymorphism allows a single piece of code to be given a "generic" type, using variables in place of actual types, and then instantiated with particular types as needed. Parametrically polymorph ...
. In such a setting, making arrays invariant rules out useful polymorphic programs. For example, consider writing a function to shuffle an array, or a function that tests two arrays for equality using the . method on the elements. The implementation does not depend on the exact type of element stored in the array, so it should be possible to write a single function that works on all types of arrays. It is easy to implement functions of type: boolean equalArrays(Object[] a1, Object[] a2); void shuffleArray(Object[] a); However, if array types were treated as invariant, it would only be possible to call these functions on an array of exactly the type . One could not, for example, shuffle an array of strings. Therefore, both Java and C# treat array types covariantly. For instance, in Java is a subtype of , and in C# is a subtype of . As discussed above, covariant arrays lead to problems with writes into the array. Java and C# deal with this by marking each array object with a type when it is created. Each time a value is stored into an array, the execution environment will check that the run-time type of the value is equal to the run-time type of the array. If there is a mismatch, an (Java) or (C#) is thrown: // 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 a java.lang.ArrayStoreException. b = 1; In the above example, one can ''read'' from the array (b) safely. It is only trying to ''write'' to the array that can lead to trouble. One drawback to this approach is that it leaves the possibility of a run-time error that a stricter type system could have caught at compile-time. Also, it hurts performance because each write into an array requires an additional run-time check. With the addition of generics, Java and C# now offer ways to write this kind of polymorphic function without relying on covariance. The array comparison and shuffling functions can be given the parameterized types boolean equalArrays(T[] a1, T[] a2); void shuffleArray(T[] a); Alternatively, to enforce that a C# method accesses a collection in a read-only way, one can use the interface instead of passing it an array .


Function types

Languages with
first-class function In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning them as the values from ...
s have
function type In computer science and mathematical logic, a function type (or arrow type or exponential) is the type of a variable or parameter to which a function has or can be assigned, or an argument or result type of a higher-order function taking or re ...
s like "a function expecting a Cat and returning an Animal" (written in OCaml syntax or in C# syntax). Those languages also need to specify when one function type is a subtype of another—that is, when it is safe to use a function of one type in a context that expects a function of a different type. It is safe to substitute a function ''f'' for a function ''g'' if ''f'' accepts a more general type of argument and returns a more specific type than ''g''. For example, functions of type , , and can be used wherever a was expected. (One can compare this to the robustness principle of communication: "be liberal in what you accept and conservative in what you produce.") The general rule is: :(P_1 \rightarrow R_1) \leq (P_2 \rightarrow R_2) if P_1 \geq P_2 and R_1 \leq R_2. Using inference rule notation the same rule can be written as: :\frac In other words, the → type constructor is ''contravariant in the parameter (input) type'' and ''covariant in the return (output) type''. This rule was first stated formally by John C. Reynolds, and further popularized in a paper by
Luca Cardelli Luca Andrea Cardelli, Fellow of the Royal Society (FRS), is an Italian computer scientist who is a research professor at the University of Oxford in Oxford, UK. Cardelli is well known for his research in type theory and operational semantics. A ...
. When dealing with functions that take functions as arguments, this rule can be applied several times. For example, by applying the rule twice, we see that ((P_1 \to R) \to R) \le ((P_2 \to R) \to R) if P_1 \le P_2. In other words, the type ((A \to B) \to C) is ''covariant'' in the position of A. For complicated types it can be confusing to mentally trace why a given type specialization is or isn't type-safe, but it is easy to calculate which positions are co- and contravariant: a position is covariant if it is on the left side of an even number of arrows applying to it.


Inheritance in object-oriented languages

When a subclass overrides a method in a superclass, the compiler must check that the overriding method has the right type. While some languages require that the type exactly matches the type in the superclass (invariance), it is also type safe to allow the overriding method to have a "better" type. By the usual subtyping rule for function types, this means that the overriding method should return a more specific type (return type covariance), and accept a more general argument (parameter type contravariance). In
UML The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system. The creation of UML was originally m ...
notation, the possibilities are as follows (where Class B is the subclass that extends Class A which is the superclass): Image:Vererbung T.svg, Subtyping of the parameter/return type of the method. Image:Inheritance_invariant.svg, ''Invariance''. The signature of the overriding method is unchanged. Image:Inheritance_covariant_return.svg, ''Covariant return type''. The subtyping relation is in the same direction as the relation between ClassA and ClassB. Image:Inheritance_contravariant_argument.svg, ''Contravariant parameter type''. The subtyping relation is in the opposite direction to the relation between ClassA and ClassB. Image:Inheritance_covariant_argument.svg, ''Covariant parameter type''. Not type safe. For a concrete example, suppose we are writing a class to model an
animal shelter An animal shelter or pound is a place where stray, lost, abandoned or surrendered animals – mostly dogs and cats – are housed. The word "pound" has its origins in the animal pounds of agricultural communities, where stray livestock would ...
. We assume that is a subclass of , and that we have a base class (using Java syntax) class AnimalShelter Now the question is: if we subclass , what types are we allowed to give to and ?


Covariant method return type

In a language which allows covariant return types, a derived class can override the method to return a more specific type: class CatShelter extends AnimalShelter Among mainstream OO languages,
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
,
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
and C# (as of version 9.0 ) support covariant return types. Adding the covariant return type was one of the first modifications of the C++ language approved by the standards committee in 1998. Scala and D also support covariant return types.


Contravariant method parameter type

Similarly, it is type safe to allow an overriding method to accept a more general argument than the method in the base class: class CatShelter extends AnimalShelter Only a few object-oriented languages actually allow this (for example, Python when typechecked with mypy). C++, Java and most other languages that support overloading and/or shadowing would interpret this as a method with an overloaded or shadowed name. However, Sather supported both covariance and contravariance. Calling convention for overridden methods are covariant with ''out'' parameters and return values, and contravariant with normal parameters (with the mode ''in'').


Covariant method parameter type

A couple of mainstream languages, Eiffel and Dart allow the parameters of an overriding method to have a ''more'' specific type than the method in the superclass (parameter type covariance). Thus, the following Dart code would type check, with overriding the method in the base class: class CatShelter extends AnimalShelter This is not type safe. By up-casting a to an , one can try to place a dog in a cat shelter. That does not meet parameter restrictions, and will result in a runtime error. The lack of type safety (known as the "catcall problem" in the Eiffel community, where "cat" or "CAT" is a Changed Availability or Type) has been a long-standing issue. Over the years, various combinations of global static analysis, local static analysis, and new language features have been proposed to remedy it, and these have been implemented in some Eiffel compilers. Despite the type safety problem, the Eiffel designers consider covariant parameter types crucial for modeling real world requirements. The cat shelter illustrates a common phenomenon: it is ''a kind of'' animal shelter but has ''additional restrictions'', and it seems reasonable to use inheritance and restricted parameter types to model this. In proposing this use of inheritance, the Eiffel designers reject the Liskov substitution principle, which states that objects of subclasses should always be less restricted than objects of their superclass. One other instance of a mainstream language allowing covariance in method parameters is PHP in regards to class constructors. In the following example, the __construct() method is accepted, despite the method parameter being covariant to the parent's method parameter. Were this method anything other than __construct(), an error would occur: interface AnimalInterface interface DogInterface extends AnimalInterface class Dog implements DogInterface class Pet class PetDog extends Pet Another example where covariant parameters seem helpful is so-called binary methods, i.e. methods where the parameter is expected to be of the same type as the object the method is called on. An example is the method: checks whether comes before or after in some ordering, but the way to compare, say, two rational numbers will be different from the way to compare two strings. Other common examples of binary methods include equality tests, arithmetic operations, and set operations like subset and union. In older versions of Java, the comparison method was specified as an interface : interface Comparable The drawback of this is that the method is specified to take an argument of type . A typical implementation would first down-cast this argument (throwing an error if it is not of the expected type): class RationalNumber implements Comparable In a language with covariant parameters, the argument to could be directly given the desired type , hiding the typecast. (Of course, this would still give a runtime error if was then called on e.g. a .)


Avoiding the need for covariant parameter types

Other language features can provide the apparent benefits of covariant parameters while preserving Liskov substitutability. In a language with ''generics'' (a.k.a.
parametric polymorphism In programming languages and type theory, parametric polymorphism allows a single piece of code to be given a "generic" type, using variables in place of actual types, and then instantiated with particular types as needed. Parametrically polymorph ...
) and bounded quantification, the previous examples can be written in a type-safe way. Instead of defining , we define a parameterized class . (One drawback of this is that the implementer of the base class needs to foresee which types will need to be specialized in the subclasses.) class Shelter class CatShelter extends Shelter Similarly, in recent versions of Java the interface has been parameterized, which allows the downcast to be omitted in a type-safe way: class RationalNumber implements Comparable Another language feature that can help is ''multiple dispatch''. One reason that binary methods are awkward to write is that in a call like , selecting the correct implementation of really depends on the runtime type of both and , but in a conventional OO language only the runtime type of is taken into account. In a language with
Common Lisp Object System The Common Lisp Object System (CLOS) is the facility for object-oriented programming which is part of ANSI Common Lisp. CLOS is a powerful dynamic object system which differs radically from the OOP facilities found in more static languages such ...
(CLOS)-style
multiple dispatch Multiple dispatch or multimethods is a feature of some programming languages in which a function or method can be dynamically dispatched based on the run-time (dynamic) type or, in the more general case, some other attribute of more than one of ...
, the comparison method could be written as a generic function where both arguments are used for method selection. Giuseppe Castagna observed that in a typed language with multiple dispatch, a generic function can have some parameters which control dispatch and some "left-over" parameters which do not. Because the method selection rule chooses the most specific applicable method, if a method overrides another method, then the overriding method will have more specific types for the controlling parameters. On the other hand, to ensure type safety the language still must require the left-over parameters to be at least as general. Using the previous terminology, types used for runtime method selection are covariant while types not used for runtime method selection of the method are contravariant. Conventional single-dispatch languages like Java also obey this rule: only one argument is used for method selection (the receiver object, passed along to a method as the hidden argument ), and indeed the type of is more specialized inside overriding methods than in the superclass. Castagna suggests that examples where covariant parameter types are superior (particularly, binary methods) should be handled using multiple dispatch; which is naturally covariant. However, most programming languages do not support multiple dispatch.


Summary of variance and inheritance

The following table summarizes the rules for overriding methods in the languages discussed above.


Generic types

In programming languages that support generics (a.k.a.
parametric polymorphism In programming languages and type theory, parametric polymorphism allows a single piece of code to be given a "generic" type, using variables in place of actual types, and then instantiated with particular types as needed. Parametrically polymorph ...
), the programmer can extend the type system with new constructors. For example, a C# interface like makes it possible to construct new types like or . The question then arises what the variance of these type constructors should be. There are two main approaches. In languages with ''declaration-site variance annotations'' (e.g., C#), the programmer annotates the definition of a generic type with the intended variance of its type parameters. With ''use-site variance annotations'' (e.g.,
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mos ...
), the programmer instead annotates the places where a generic type is instantiated.


Declaration-site variance annotations

The most popular languages with declaration-site variance annotations are C# and Kotlin (using the keywords and ), and Scala and OCaml (using the keywords and ). C# only allows variance annotations for interface types, while Kotlin, Scala and OCaml allow them for both interface types and concrete data types.


Interfaces

In C#, each type parameter of a generic interface can be marked covariant (), contravariant (), or invariant (no annotation). For example, we can define an interface of read-only iterators, and declare it to be covariant (out) in its type parameter. interface IEnumerator With this declaration, will be treated as covariant in its type parameter, e.g. is a subtype of . The type checker enforces that each method declaration in an interface only mentions the type parameters in a way consistent with the / annotations. That is, a parameter that was declared covariant must not occur in any contravariant positions (where a position is contravariant if it occurs under an odd number of contravariant type constructors). The precise rule is that the return types of all methods in the interface must be ''valid covariantly'' and all the method parameter types must be ''valid contravariantly'', where ''valid S-ly'' is defined as follows: * Non-generic types (classes, structs, enums, etc.) are valid both co- and contravariantly. * A type parameter is valid covariantly if it was not marked , and valid contravariantly if it was not marked . * An array type is valid S-ly if is. (This is because C# has covariant arrays.) * A generic type is valid S-ly if for each parameter , ** Ai is valid S-ly, and the ''i''th parameter to is declared covariant, or ** Ai is valid (not S)-ly, and the ''i''th parameter to is declared contravariant, or ** Ai is valid both covariantly and contravariantly, and the ''i''th parameter to is declared invariant. As an example of how these rules apply, consider the interface. interface IList The parameter type of must be valid contravariantly, i.e. the type parameter must not be tagged . Similarly, the result type of must be valid covariantly, i.e. (since is a covariant interface) the type must be valid covariantly, i.e. the type parameter must not be tagged . This shows that the interface is not allowed to be marked either co- or contravariant. In the common case of a generic data structure such as , these restrictions mean that an parameter can only be used for methods getting data out of the structure, and an parameter can only be used for methods putting data into the structure, hence the choice of keywords.


Data

C# allows variance annotations on the parameters of interfaces, but not the parameters of classes. Because fields in C# classes are always mutable, variantly parameterized classes in C# would not be very useful. But languages which emphasize immutable data can make good use of covariant data types. For example, in all of Scala, Kotlin and OCaml the immutable list type is covariant: List at/syntaxhighlight> is a subtype of List
nimal Nimal may refer to *Nimal Bandara, Sri Lankan politician *Nimal Gamini Amaratunga, Sri Lankan judge *Nimal Gunaratne, Sri Lankan air force officer *Nimal Mendis, Sri Lankan politician *Nimal Piyatissa (born 1968), Sri Lankan politician *Nimal Raja ...
/syntaxhighlight>. Scala's rules for checking variance annotations are essentially the same as C#'s. However, there are some idioms that apply to immutable datastructures in particular. They are illustrated by the following (excerpt from the) definition of the List /syntaxhighlight> class. sealed abstract class List Aextends AbstractSeq First, class members that have a variant type must be immutable. Here, head has the type A, which was declared covariant (+), and indeed head was declared as a method (def). Trying to declare it as a mutable field (var) would be rejected as type error. Second, even if a data structure is immutable, it will often have methods where the parameter type occurs contravariantly. For example, consider the method :: which adds an element to the front of a list. (The implementation works by creating a new object of the similarly named ''class'' ::, the class of nonempty lists.) The most obvious type to give it would be def :: (x: A): List However, this would be a type error, because the covariant parameter A appears in a contravariant position (as a function parameter). But there is a trick to get around this problem. We give :: a more general type, which allows adding an element of any type B as long as B is a supertype of A. Note that this relies on List being covariant, since this has type List /syntaxhighlight> and we treat it as having type List /syntaxhighlight>. At first glance it may not be obvious that the generalized type is sound, but if the programmer starts out with the simpler type declaration, the type errors will point out the place that needs to be generalized.


Inferring variance

It is possible to design a type system where the compiler automatically infers the best possible variance annotations for all datatype parameters. However, the analysis can get complex for several reasons. First, the analysis is nonlocal since the variance of an interface depends on the variance of all interfaces that mentions. Second, in order to get unique best solutions the type system must allow ''bivariant'' parameters (which are simultaneously co- and contravariant). And finally, the variance of type parameters should arguably be a deliberate choice by the designer of an interface, not something that just happens. For these reasons most languages do very little variance inference. C# and Scala do not infer any variance annotations at all. OCaml can infer the variance of parameterized concrete datatypes, but the programmer must explicitly specify the variance of abstract types (interfaces). For example, consider an OCaml datatype which wraps a function type ('a, 'b) t = T of ('a -> 'b) The compiler will automatically infer that is contravariant in the first parameter, and covariant in the second. The programmer can also provide explicit annotations, which the compiler will check are satisfied. Thus the following declaration is equivalent to the previous one: type (-'a, +'b) t = T of ('a -> 'b) Explicit annotations in OCaml become useful when specifying interfaces. For example, the standard library interface for association tables include an annotation saying that the map type constructor is covariant in the result type. module type S = sig type key type (+'a) t val empty: 'a t val mem: key -> 'a t -> bool ... end This ensures that e.g. is a subtype of .


Use-site variance annotations (wildcards)

One drawback of the declaration-site approach is that many interface types must be made invariant. For example, we saw above that needed to be invariant, because it contained both and . In order to expose more variance, the API designer could provide additional interfaces which provide subsets of the available methods (e.g. an "insert-only list" which only provides ). However this quickly becomes unwieldy. Use-site variance means the desired variance is indicated with an annotation at the specific site in the code where the type will be used. This gives users of a class more opportunities for subtyping without requiring the designer of the class to define multiple interfaces with different variance. Instead, at the point a generic type is instantiated to an actual parameterized type, the programmer can indicate that only a subset of its methods will be used. In effect, each definition of a generic class also makes available interfaces for the covariant and contravariant ''parts'' of that class. Java provides use-site variance annotations through wildcards, a restricted form of bounded existential types. A parameterized type can be instantiated by a wildcard together with an upper or lower bound, e.g. or . An unbounded wildcard like is equivalent to . Such a type represents for some unknown type which satisfies the bound. For example, if has type , then the type checker will accept Animal a = l.get(3); because the type is known to be a subtype of , but l.add(new Animal()); will be rejected as a type error since an is not necessarily an . In general, given some interface , a reference to an forbids using methods from the interface where occurs contravariantly in the type of the method. Conversely, if had type one could call but not . While non-wildcard parameterized types in Java are invariant (e.g. there is no subtyping relationship between and ), wildcard types can be made more specific by specifying a tighter bound. For example, is a subtype of . This shows that wildcard types are ''covariant in their upper bounds'' (and also ''contravariant in their lower bounds''). In total, given a wildcard type like , there are three ways to form a subtype: by specializing the class , by specifying a tighter bound , or by replacing the wildcard with a specific type (see figure). By applying two of the above three forms of subtyping, it becomes possible to, for example, pass an argument of type to a method expecting a . This is the kind of expressiveness that results from covariant interface types. The type acts as an interface type containing only the covariant methods of , but the implementer of did not have to define it ahead of time. In the common case of a generic data structure , covariant parameters are used for methods getting data out of the structure, and contravariant parameters for methods putting data into the structure. The mnemonic for Producer Extends, Consumer Super (PECS), from the book ''Effective Java'' by
Joshua Bloch Joshua J. Bloch (born August 28, 1961) is an American software engineer and a technology author, formerly employed at Sun Microsystems and Google. He led the design and implementation of numerous Java platform features, including the Java Collect ...
gives an easy way to remember when to use covariance and contravariance. Wildcards are flexible, but there is a drawback. While use-site variance means that API designers need not consider variance of type parameters to interfaces, they must often instead use more complicated method signatures. A common example involves the interface. Suppose we want to write a function that finds the biggest element in a collection. The elements need to implement the method, so a first try might be > T max(Collection coll); However, this type is not general enough—one can find the max of a , but not a . The problem is that does not implement , but instead the (better) interface . In Java, unlike in C#, is not considered a subtype of . Instead the type of has to be modified: > T max(Collection coll); The bounded wildcard conveys the information that calls only contravariant methods from the interface. This particular example is frustrating because ''all'' the methods in are contravariant, so that condition is trivially true. A declaration-site system could handle this example with less clutter by annotating only the definition of .


Comparing declaration-site and use-site annotations

Use-site variance annotations provide additional flexibility, allowing more programs to type check. However, they have been criticized for the complexity they add to the language, leading to complicated type signatures and error messages. One way to assess whether the extra flexibility is useful is to see if it is used in existing programs. A survey of a large set of Java libraries found that 39% of wildcard annotations could have been directly replaced by declaration-site annotations. Thus the remaining 61% is an indication of places where Java benefits from having the use-site system available. In a declaration-site language, libraries must either expose less variance, or define more interfaces. For example, the Scala Collections library defines three separate interfaces for classes which employ covariance: a covariant base interface containing common methods, an invariant mutable version which adds side-effecting methods, and a covariant immutable version which may specialize the inherited implementations to exploit structural sharing. This design works well with declaration-site annotations, but the large number of interfaces carry a complexity cost for clients of the library. And modifying the library interface may not be an option—in particular, one goal when adding generics to Java was to maintain binary backwards compatibility. On the other hand, Java wildcards are themselves complex. In a conference presentation
Joshua Bloch Joshua J. Bloch (born August 28, 1961) is an American software engineer and a technology author, formerly employed at Sun Microsystems and Google. He led the design and implementation of numerous Java platform features, including the Java Collect ...
criticized them as being too hard to understand and use, stating that when adding support for closures "we simply cannot afford another ''wildcards''". Early versions of Scala used use-site variance annotations but programmers found them difficult to use in practice, while declaration-site annotations were found to be very helpful when designing classes. Later versions of Scala added Java-style existential types and wildcards; however, according to
Martin Odersky Martin Odersky (born 5 September 1958) is a German computer scientist and professor of programming methods at École Polytechnique Fédérale de Lausanne (EPFL) in Switzerland. He specializes in code analysis and programming languages. He designe ...
, if there were no need for interoperability with Java then these would probably not have been included. Ross Tate argues that part of the complexity of Java wildcards is due to the decision to encode use-site variance using a form of existential types. The original proposals used special-purpose syntax for variance annotations, writing instead of Java's more verbose . Since wildcards are a form of existential types they can be used for more things than just variance. A type like ("a list of unknown type") lets objects be passed to methods or stored in fields without exactly specifying their type parameters. This is particularly valuable for classes such as where most of the methods do not mention the type parameter. However,
type inference Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistic ...
for existential types is a difficult problem. For the compiler implementer, Java wildcards raise issues with type checker termination, type argument inference, and ambiguous programs. In general it is undecidable whether a Java program using generics is well-typed or not, so any type checker will have to go into an infinite loop or time out for some programs. For the programmer, it leads to complicated type error messages. Java type checks wildcard types by replacing the wildcards with fresh type variables (so-called ''capture conversion''). This can make error messages harder to read, because they refer to type variables that the programmer did not directly write. For example, trying to add a to a will give an error like method List.add (capture#1) is not applicable (actual argument Cat cannot be converted to capture#1 by method invocation conversion) where capture#1 is a fresh type-variable: capture#1 extends Animal from capture of ? extends Animal Since both declaration-site and use-site annotations can be useful, some type systems provide both.


Etymology

These terms come from the notion of covariant and contravariant functors in category theory. Consider the category C whose objects are types and whose morphisms represent the subtype relationship ≤. (This is an example of how any partially ordered set can be considered as a category.) Then for example the function type constructor takes two types ''p'' and ''r'' and creates a new type ''p'' → ''r''; so it takes objects in C^2 to objects in C. By the subtyping rule for function types this operation reverses ≤ for the first parameter and preserves it for the second, so it is a contravariant functor in the first parameter and a covariant functor in the second.


See also

*
Polymorphism (computer science) In programming language theory and type theory, polymorphism is the provision of a single interface (computing), interface to entities of different Data type, types or the use of a single symbol to represent multiple different types.: "Polymorph ...
* Inheritance (computer science) * Liskov substitution principle


References


External links


Fabulous Adventures in Coding
An article series about implementation concerns surrounding co/contravariance in C#
Contra Vs Co Variance
(note this article is not updated about C++)


The theory behind covariance and contravariance in C# 4
{{DEFAULTSORT:Covariance And Contravariance (Computer Science) Object-oriented programming Type theory Polymorphism (computer science)