liveBook · Manning

Out position

As explained in Kotlin in Action, 2E

An out position is a type-parameter usage position in which values of the parameterized type are produced rather than consumed.

An out position is a place where a generic type parameter produces a value rather than consumes one. A function return type puts T in the out position; a function parameter puts T in the in position. Kotlin's out modifier requires every use of T to remain in out positions, making covariance type-safe. section 11.3.3

A covariant producer

interface Producer<out T> { fun produce(): T } Here, produce returns T, so T is used only in an out position. Producer<Cat> can therefore be used where Producer<Animal> is expected: the producer supplies an Animal-compatible value, but callers cannot pass arbitrary Animals into it. section 11.3.3

A collection-like Herd demonstrates the practical benefit. Herd<out T> can be passed to feedAll, which expects Herd<Animal>, when the actual herd is Herd<Cat>. Kotlin's read-only List follows the same producer pattern, while MutableList cannot safely accept the same covariance because add consumes T.

How Kotlin in Action, 2E covers it

How deep it goes
Explains return and parameter positions, declaration-site restrictions, covariance, and collection examples without descending into runtime implementation.
Examples
Uses Producer, Herd<Cat>, Herd<Animal>, List, and MutableList to contrast producing values with consuming them.
What it assumes
Assumes generic type parameters and subtyping, then defines positional use through simple function returns and parameters.
What you can do after
Apply it via Kotlin's out modifier to design producer-like generic types with safe covariance.
How it connects
Connects out positions to covariance, variance, generic types, read-only List, MutableList, and contravariance.

Also explained in

Compare how 2 books explain out position →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.