Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 13 / Topic 3 of 7

Declaration-site variance: out and in

By default, generics in Kotlin are invariant: Crate<String> and Crate<Any> are unrelated types, even though every String is an Any. That's a safe default, but it's needlessly strict for a class that only ever hands out T, or only ever takes in T.

out marks a type parameter that a class only produces -- it only ever appears as a return type, never as a parameter type. Declaring it out makes the class covariant: a ReadOnlyBin<String> can stand in anywhere a ReadOnlyBin<Any> is expected, because anything you can do with the Any you get back, you could already do with the String.

class ReadOnlyBin<out T>(private val item: T) {
    fun peek(): T = item
}

fun describeAny(bin: ReadOnlyBin<Any>) = println("Bin holds: ${bin.peek()}")

in marks a type parameter a class only consumes -- only ever a parameter type, never a return type. That makes the class contravariant: a Scanner<Any> can stand in anywhere a Scanner<String> is expected, because something that can scan any object can certainly scan a String.

interface Scanner<in T> {
    fun scan(item: T): String
}

class AnyScanner : Scanner<Any> {
    override fun scan(item: Any) = "scanned: $item"
}
val riceBin: ReadOnlyBin<String> = ReadOnlyBin("Basmati Rice 5kg")
describeAny(riceBin)

val anyScanner = AnyScanner()
val productScanner: Scanner<String> = anyScanner
println(productScanner.scan("S-4821"))
Bin holds: Basmati Rice 5kg
scanned: S-4821

The direction is easy to remember once you say it out loud: "out" flows out of the class (it only produces), "in" flows in (it only consumes). Try adding a method that both takes and returns T to ReadOnlyBin<out T> and the compiler rejects it outright -- out genuinely restricts what the class is allowed to do, in exchange for the variance.

Full program: examples/03_declaration_site_variance.kt.

Done here? The practice set for Part 13 — including the solutions — is on the part page.

Search the guide