0
0
KotlinConceptBeginner · 3 min read

What is out keyword in Kotlin: Explanation and Examples

In Kotlin, the out keyword is used to declare a generic type as covariant, meaning it can only be returned (produced) but not consumed (accepted) by functions. It allows safe use of subtypes, like reading from a list of a base type while allowing a list of a subtype.
⚙️

How It Works

Think of the out keyword as a way to say "I only give out values of this type, but I don't take any in." This means you can safely use a subtype where a supertype is expected without risking type errors. For example, if you have a box that only produces items of type T, marking T with out means you can use a box of a subtype wherever a box of a supertype is needed.

This is called covariance. It helps Kotlin keep your code safe by preventing you from putting the wrong type into a container that promises to only give out certain types. The compiler enforces this by allowing only output positions (like return types) to use out types, not input positions (like function parameters).

💻

Example

This example shows a generic interface with out keyword, allowing safe covariance.

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) // Allowed because of 'out'
}
Output
Hello
🎯

When to Use

Use the out keyword when you want to make a generic type covariant, meaning it only produces values and never consumes them. This is common in producer-only interfaces or classes, like streams, iterators, or read-only collections.

For example, if you have a list that you only read from, marking its type parameter with out allows you to pass a list of a subtype where a list of a supertype is expected. This helps write flexible and type-safe APIs.

Key Points

  • out marks a generic type as covariant (producer-only).
  • It allows safe substitution of subtypes for supertypes.
  • Types marked out can only be returned, not accepted as parameters.
  • Commonly used in read-only or producer interfaces.

Key Takeaways

The out keyword makes a generic type covariant, allowing safe use of subtypes.
It restricts the type to be used only as output (return values), not input (parameters).
Use out for producer-only interfaces or read-only collections.
Covariance helps write flexible and type-safe Kotlin code.