liveBook · Manning

Type projection

As explained in Kotlin in Action, 2E

A type projection is a restricted view of a parameterized type that permits only operations allowed by a use-site variance constraint.

Type projection gives a parameterized type a restricted view. An out projection permits reading the type parameter but prevents passing values into it; an in projection permits the opposite direction. This lets functions express the operations they actually need. section 11.3.5

Copying through an out projection

fun <T> copyData(source: MutableList<out T>, destination: MutableList<T>) { for (item in source) destination.add(item) } The source can provide T values, but source.add(...) is rejected. For example, MutableList<out Number> cannot accept 42 because its exact element type is unknown. Use a regular type when the function must call prohibited methods; alternatively, separate the source and destination types with a bound such as <T: R, R>.

Accepting values with an in projection

fun <T> copyData(source: MutableList<T>, destination: MutableList<in T>) { for (item in source) destination.add(item) } The destination is treated as a consumer of T values.

How Kotlin in Action, 2E covers it

How deep it goes
Defines projections, demonstrates copy functions, and explains compiler-rejected operations and redundant projections.
Examples
Uses copyData with MutableList<out T>, MutableList<in T>, and a rejected add operation on MutableList<out Number>.
What you can do after
Apply type projections to constrain function parameters and let the compiler prevent unsafe operations.
How it connects
Connects use-site variance with generic types, mutable lists, covariance, and contravariance.

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.