🐦 Kotlin Advanced

What is contravariance (in) in Kotlin generics?

Answer

Contravariance, declared with the in keyword, means a generic class is a consumer of values of that type — it can only accept (consume) values but cannot produce them. This reverses the subtype relationship: a Comparator<Animal> can be used where a Comparator<Dog> is expected, because a comparator that can compare any Animal can certainly compare Dogs. interface Consumer<in T> { fun consume(value: T) }. If Dog is a subtype of Animal, then Consumer<Animal> is a subtype of Consumer<Dog> — the relationship is reversed (contra-variant).