Junior — Middle
Selgitage kovariansi kontseptsiooni Kotlinis generikates ja selle rakendamist
sobes.tech AI
Vastus AI-lt
Kovariance in Kotlin is a property of generics that allows using a more specific type instead of the base type when reading data. It is indicated 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 the generic is used only for output (reading) of data, not for input. 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