Opentopia Directory Encyclopedia Tools

Covariance and contravariance (computer science)

Encyclopedia : C : CO : COV : Covariance and contravariance (computer science)



 

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

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.

The issue is somewhat implicit in object-oriented design and programming in general, but becomes explicit in generic programming, for example.

Language support

C++

C++ supports covariant return types in overridden virtual functions.

C#

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. This could result in a lack of source-compatibility with code written for earlier versions of the language, but only in somewhat contrived examples.

Neither covariance nor contravariance are supported for method overrriding.

Eiffel

In Eiffel you can get compiler errors, because polymorphism breaks.

Java

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.

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.

Scala

Scala supports both covariance and contravariance.

Sather

So does Sather.

See also

External links

 


From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.


Search Titles
0123456789
ABCDEFGHIJ
KLMNOPQRST
UVWXYZ?

E-mail this article to:

Personal Message: