Sobes.tech
Junior — Middle

Explain the concept of covariance in generics in Kotlin and its application

sobes.tech AI

Answer from AI

Covariance in Kotlin is a property of generics that allows using a more specific type instead of a base type when reading data. It is denoted by the keyword out in the type declaration, for example, interface Producer<out T>. This means that Producer<Cat> can be used where Producer<Animal> is expected, if Cat inherits from Animal.

Using covariance is useful when a generic is used only for output (reading) data, not for input (writing). It ensures type safety and API flexibility.

Example:

open class Animal
class Cat : Animal()

interface Producer<out T> {
    fun produce(): T
}

fun feedAnimals(animals: Producer<Animal>) {
    val animal = animals.produce()
    // feed the animal
}

val catsProducer: Producer<Cat> = object : Producer<Cat> {
    override fun produce() = Cat()
}

feedAnimals(catsProducer) // Works thanks to covariance