Home >Backend Development >C++ >Covariance vs. Contravariance: How Do These Concepts Differ in Programming?
Covariance and Contravariance: A Clear Distinction in Programming
Covariance and contravariance are fundamental concepts in programming that define how type relationships influence function mappings and data structure input/output types. Essentially, covariance preserves assignability direction, while contravariance reverses it.
Covariance: Maintaining Assignability
Let's illustrate with type sets:
<code>{ Animal, Tiger, Fruit, Banana } { IEnumerable<Animal>, IEnumerable<Tiger>, IEnumerable<Fruit>, IEnumerable<Banana> }</code>
The mapping T → IEnumerableTiger
is a subtype of Animal
, then IEnumerable<Tiger>
is also a subtype of IEnumerable<Animal>
. This is common in container types, where subtyping applies to the contained elements.
Contravariance: Inverting Assignability
Now, consider these type sets:
<code>{ IComparable<Tiger>, IComparable<Animal>, IComparable<Fruit>, IComparable<Banana> }</code>
The mapping T → IComparableAnimal
is a supertype of Tiger
, then IComparable<Animal>
is a subtype of IComparable<Tiger>
. This is frequently observed in functional types, where contravariant types manage input parameters of specific or related types.
Key Differences Summarized
Covariance upholds assignability direction; a subtype value can be assigned to a supertype value in both function input and output. In contrast, contravariance inverts assignability, enabling a supertype value assignment to a subtype value in the input parameter, but not in the output.
The above is the detailed content of Covariance vs. Contravariance: How Do These Concepts Differ in Programming?. For more information, please follow other related articles on the PHP Chinese website!