Covariance in Kotlin is a type-system feature that preserves the subtyping relationship of generic type parameters. 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.
A is a subtype of type B, a covariant generic type Generic<A> is considered a subtype of Generic<B>. Kotlin implements covariance through two mechanisms: declaration-site variance using the out modifier, and use-site variance through type projections.
Declaration-Site Variance
By marking a type parameter without at the class or interface declaration, you instruct the compiler to restrict the usage of that type parameter strictly to out positions (return types and read-only val properties). The type can only be produced by the generic component, never consumed as an argument.
Type Safety and the out Restriction
The compiler enforces the “produce-only” rule to prevent heap pollution and runtime ClassCastExceptions. If a covariant type parameter were allowed in an in position (such as a function parameter or a mutable property), the type system could be compromised.
Using var with an out type parameter in a primary constructor is immediately illegal. The var keyword generates a setter, which places the type parameter in an in position, causing a compilation error on the property declaration itself.
out parameters to read-only positions, a covariant Box<Animal> can only ever return an Animal (which is safely guaranteed to be a Dog in the underlying instance), and the compiler prevents you from writing a Cat into it.
Use-Site Variance (Type Projections)
Certain types, such asArray or MutableList, must remain invariant at the declaration site because they both produce and consume elements. To achieve covariance for these types for a specific operation, Kotlin uses use-site variance, also known as type projections.
By applying the out modifier at the point of usage, you project the invariant type into a covariant one. This restricts the projected instance to its “produce” methods, effectively disabling any methods that consume the type parameter.
@UnsafeVariance
In specific architectural scenarios, a type parameter must be covariant at the declaration site, but technically needs to appear in anin position where the internal implementation guarantees type safety (e.g., checking equality). Kotlin provides the @UnsafeVariance annotation to suppress the compiler’s variance conflict errors.
Master Kotlin with Deep Grasping Methodology!Learn More





