liveBook · Manning

In position

As explained in Kotlin in Action, 2E

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

An in position is a type-parameter usage position where a function consumes values of that type. A type parameter appears in the in position when it is used as a function parameter type. section 11.3.3

A consumer of T

interface Consumer<in T> { fun consume(value: T) } Here, value has type T, so consume consumes T values. The in keyword restricts T to in positions and supports contravariant subtyping: a generic class can be declared contravariant when its parameter is used only in in positions. section 11.3.3 section 11.4

Distinguish the two positions by asking what the function does with T:

  • A parameter of type T consumes a T value and places T in the in position. section 11.3.3
  • A return type of T produces a T value and places T in the out position. section 11.3.3
  • Using T as a type argument of another type also requires checking the resulting position. section 11.3.3

The distinction explains why a covariant parameter marked out cannot be consumed: allowing T in an in position would make its subtype relation unsafe. Read-only List remains covariant because it returns T but does not store T values. section 11.3.3

How Kotlin in Action, 2E covers it

How deep it goes
Defines parameter and return positions, then connects them to covariance, contravariance, and nested type-argument checks.
Examples
Uses a consuming function parameter, covariant Herd, and read-only List to contrast in and out positions.
What it assumes
Assumes generic type parameters and function signatures while defining positional variance through parameter and return types.
What you can do after
Apply it via Kotlin variance declarations by identifying whether each type-parameter use consumes or produces values.
How it connects
Connects in positions with contravariance, out positions, covariance, generic type parameters, and Kotlin List.

Also explained in

Compare how 2 books explain in 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.