0
0
Kotlinprogramming~5 mins

Out variance (covariance) in Kotlin

Choose your learning style9 modes available
Introduction

Out variance helps Kotlin know that a type can only be produced (output) but not consumed (input). This makes code safer and easier to use.

When you want to return a list of animals but don't want to allow adding new animals to it.
When you create a function that produces values of a generic type but never consumes them.
When you want to pass a read-only collection to a function without risking modification.
When you want to make your API more flexible by allowing subtypes to be used safely.
Syntax
Kotlin
interface Producer<out T> {
    fun produce(): T
}

The out keyword means the generic type T can only be returned (output).

You cannot use T as a parameter type in functions inside this interface.

Examples
This interface produces values of type T. You can get T but not put it in.
Kotlin
interface Source<out T> {
    fun next(): T
}
This function copies elements from a source array that can be any subtype of Any. The out keyword allows safe reading.
Kotlin
fun copy(from: Array<out Any>, to: Array<Any>) {
    for (i in from.indices) {
        to[i] = from[i]
    }
}
Sample Program

This program shows how out allows a Producer<String> to be used where Producer<Any> is expected. It prints the produced string.

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

class StringProducer : Producer<String> {
    override fun produce(): String = "Hello"
}

fun printProduced(producer: Producer<Any>) {
    println(producer.produce())
}

fun main() {
    val stringProducer: Producer<String> = StringProducer()
    printProduced(stringProducer) // Works because of out variance
}
OutputSuccess
Important Notes

Out variance only allows the generic type to be returned, not accepted as input.

It helps Kotlin keep type safety while allowing flexible use of subtypes.

Try to use out when your generic type is only used for output.

Summary

Out variance means a generic type is only used for output (producing values).

It allows safe use of subtypes, making code more flexible and safe.

Use out keyword in Kotlin interfaces or classes to declare covariance.