# Contravariance

DevFeed: [Contravariance](<https://devfeed.tech/articles/contravariance-25010.md>)

Original publisher: [Read original article](<https://typealias.com/concepts/contravariance/>)

Author: author@typealias.com (Dave Leeds)

Published: 2017-11-17T01:58:28Z

Content type: article

Language: en

Sources: [Dave Leeds on Kotlin - typealias.com](<https://devfeed.tech/sources/dave-leeds-on-kotlin-typealias-com.md>)

Topics: [Contravariance](<https://devfeed.tech/topics/contravariance.md>), [generic programming](<https://devfeed.tech/topics/generic-programming.md>), [Type Parameter](<https://devfeed.tech/topics/type-parameter.md>), [Inheritance](<https://devfeed.tech/topics/inheritance.md>), [subclass](<https://devfeed.tech/topics/subclass.md>), [class](<https://devfeed.tech/topics/class.md>)

Tags: [class](<https://devfeed.tech/tags/class.md>), [classes](<https://devfeed.tech/tags/classes.md>), [contravariance](<https://devfeed.tech/tags/contravariance.md>), [function](<https://devfeed.tech/tags/function.md>), [functions](<https://devfeed.tech/tags/functions.md>), [generic](<https://devfeed.tech/tags/generic.md>), [generics](<https://devfeed.tech/tags/generics.md>), [inheritance](<https://devfeed.tech/tags/inheritance.md>), [invariant](<https://devfeed.tech/tags/invariant.md>), [java](<https://devfeed.tech/tags/java.md>), [kotlin](<https://devfeed.tech/tags/kotlin.md>), [programming](<https://devfeed.tech/tags/programming.md>), [subtype](<https://devfeed.tech/tags/subtype.md>), [type-parameter](<https://devfeed.tech/tags/type-parameter.md>), [types](<https://devfeed.tech/tags/types.md>), [variance](<https://devfeed.tech/tags/variance.md>)

## AI overview

Contravariance reverses the subtype relationship of a generic type's parameter: if Dog is a subtype of Animal, a contravariant generic for Animal can be used where one for Dog is expected. The excerpt says to mark the type parameter with the language's contravariance annotation; without it, the generic is invariant. The tradeoff is that an instance cannot return a result of type T, since it promises only to accept values of that type. The excerpt also notes that covariant return types are allowed in many languages, including Java and Kotlin, while most languages do not allow contravariant method argument types.

## Source excerpt

Most of the time, subtyping is intuitive. Object-oriented programmers are used to the concept of inheritance, where one class specializes another, and we're familiar with the idea of passing, say, a Dog object where a function expects an Animal. Once you start working with generics, though, there are some fascinating twists that flip our typical understanding of subtyping on its head. What is Contravariance? Contravariance describes a relationship between two sets of types where they subtype in opposite directions.