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

Part 13 / Topic 4 of 7

Use-site variance and star projections

Sometimes a type itself is invariant by design -- Array<T> in Kotlin is, because arrays support both reading and writing -- but one particular function only ever reads, or only ever writes. Use-site variance puts out/in on the parameter type at the call site, instead of on the class declaration:

// Use-site `out`: this only READS, so it accepts an Array of ANY subtype of Any.
fun printAll(items: Array<out Any>) {
    for (item in items) println("  - $item")
}

// Use-site `in`: this only WRITES, so it accepts an Array of ANY supertype of Int.
fun fillWithZero(target: Array<in Int>) {
    for (i in target.indices) target[i] = 0
}
val productNames: Array<String> = arrayOf("Rice", "Dal", "Oil")
printAll(productNames)

val prices: Array<Any> = arrayOf(199.0, "N/A", 45.0)
fillWithZero(prices)
println(prices.toList())
  - Rice
  - Dal
  - Oil
[0, 0, 0]

Without out, printAll would only accept an Array<Any> exactly, rejecting the Array<String> -- Array<T> has no built-in variance the way List<T> does (the standard library already declares List<out T>, which is why List<out Any> would be flagged as a redundant projection).

A star projection (*) says "a generic type with some type argument, I don't need to know which" -- useful when you only need the members that don't mention the type parameter at all:

class Store<T> {
    private val items = mutableListOf<T>()
    fun add(item: T) = items.add(item)
    val size: Int get() = items.size
}

fun describeStore(store: Store<*>) {
    println("Store holds ${store.size} item(s) of an unknown type")
}
Store holds 2 item(s) of an unknown type
Store holds 1 item(s) of an unknown type

describeStore can take a Store<String> or a Store<Double> through the same parameter, because size never touches T -- but it could not call store.add(...), because the compiler genuinely doesn't know what T is inside that function.

Full program: examples/04_use_site_variance_and_star_projections.kt.

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

Search the guide