In Kotlin, contravariance helps you use a more general type where a more specific type is expected. It makes your code flexible and safe when working with types that consume data.
In variance (contravariance) in Kotlin
interface Consumer<in T> { fun consume(item: T) }
The in keyword before the generic type T marks it as contravariant.
Contravariant types can only be used as input (parameters), not as output (return types).
T. The in keyword means it can accept T or any supertype of T.interface Consumer<in T> { fun consume(item: T) }
Int. Thanks to contravariance, you can pass a Consumer<Number> safely.fun feedConsumer(consumer: Consumer<Int>) { consumer.consume(42) consumer.consume(100) }
Consumer<Number> can be assigned to a Consumer<Int> variable.val numberConsumer: Consumer<Number> = object : Consumer<Number> { override fun consume(item: Number) { println("Consumed: $item") } } val intConsumer: Consumer<Int> = numberConsumer
This program shows contravariance by assigning a Consumer to a Consumer variable. The feedConsumer function calls consume with different Int types.
interface Consumer<in T> { fun consume(item: T) } class NumberConsumer : Consumer<Number> { override fun consume(item: Number) { println("Consumed Number: $item") } } fun feedConsumer(consumer: Consumer<Int>) { consumer.consume(10) consumer.consume(20) } fun main() { val numberConsumer = NumberConsumer() // Contravariance allows this assignment val intConsumer: Consumer<Int> = numberConsumer feedConsumer(intConsumer) }
Contravariant types cannot be returned from functions because they are only safe as inputs.
Use in only when the generic type is used as a function parameter, never as a return type.
Contravariance is the opposite of covariance, which uses out and allows returning types.
Use in to mark a generic type as contravariant, meaning it can accept supertypes safely.
Contravariance is useful for consumers that only take input and never produce output.
It helps make your Kotlin code more flexible and type-safe when working with generic types.