Overview - In variance (contravariance)
What is it?
In Kotlin, contravariance is a way to make a generic type accept more general types than originally specified. It allows a type to be substituted with its supertypes, making the code more flexible when consuming data. This is done using the 'in' keyword before a generic type parameter. Contravariance is mainly used when a generic type only consumes values of a certain type but does not produce them.
Why it matters
Without contravariance, you would have to write many similar classes or functions for each specific type, making your code less reusable and harder to maintain. Contravariance solves this by allowing you to write more general and flexible code that can work with a range of types safely. This reduces bugs and improves code clarity, especially when dealing with collections or functions that only take inputs.
Where it fits
Before learning contravariance, you should understand Kotlin generics and basic variance concepts like covariance. After mastering contravariance, you can explore advanced topics like declaration-site variance, use-site variance, and how variance affects function types and collections in Kotlin.