Contravariance is a generic type system feature that reverses the standard subtyping relationship between parameterized types. In Kotlin, if typeDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
Sub is a subtype of type Super, a contravariant generic type Generic<T> establishes that Generic<Super> is a subtype of Generic<Sub>. This allows a generic instance typed to a superclass to be safely assigned to a reference typed to a subclass.
Kotlin implements contravariance using the in variance annotation. This modifier restricts the generic type parameter so that it can only be consumed (passed as input arguments to functions) and never produced (returned from functions or exposed as public properties).
Declaration-Site Variance
When thein modifier is applied at the class or interface declaration, it is known as declaration-site variance. The Kotlin compiler enforces the “in-position” restriction across the entire type.
Subtyping Mechanics
The reversal of the subtyping relationship is the core mechanic of contravariance. Because aConsumer<Super> can handle any instance of Super, it is logically safe to treat it as a Consumer<Sub>, since Sub is guaranteed to possess all the traits of Super.
Type Safety Enforcement
The compiler strictly enforces thein restriction to prevent runtime ClassCastExceptions. If a contravariant type were permitted to return T, type safety would collapse.
If Handler<in T> allowed a function fun get(): T, the following invalid state would compile:
animalHandleris assigned todogHandler.animalHandler.get()internally returns aCat(which is valid forHandler<Animal>).dogHandler.get()expects aDog, but receives theCatfrom the underlyinganimalHandler.
T to input positions, the compiler guarantees that the generic type only ever receives data it is equipped to handle, and never promises to return data of a specific subclass.
Use-Site Variance (Type Projections)
If a generic class is invariant (declared withoutin or out), contravariance can be applied at the point of usage. This is called a type projection. It restricts the API of the invariant class for that specific reference, hiding any methods where T appears in an out position.
Master Kotlin with Deep Grasping Methodology!Learn More





