Sobes.tech
Junior — Middle

Explain the concept of invariance in Kotlin generics and why it is used.

sobes.tech AI

Answer from AI

In Kotlin, invariance means that if you have a generic type Generic<T>, then Generic<A> and Generic<B> are not related by inheritance, even if A is a subtype of B. That is, Generic<A> is not a subtype of Generic<B>, and vice versa.

This is important to avoid type errors when working with mutable data structures. For example, if MutableList<String> were a subtype of MutableList<Any>, you could add an object of another type to the list of strings, which would break type safety.

In Kotlin, invariance is the default for mutable collections and other types where content modification is possible. To provide flexibility, covariance (out) and contravariance (in) are used, which allow safe extension or narrowing of types in certain cases.

Example of an invariant type:

class Box<T>(var value: T)

val boxString: Box<String> = Box("text")
// val boxAny: Box<Any> = boxString // Compilation error: Box<String> is not a subtype of Box<Any>

Thus, invariance helps maintain strict type safety when working with generic types.