liveBook · Manning

Out keyword

As explained in Kotlin in Action, 2E

The out modifier declares covariant use of a Kotlin type parameter so a parameterized type can accept subtype arguments.

The out modifier declares covariance: if Cat is a subtype of Animal, Herd<Cat> can be used where Herd<Animal> is expected. This is useful for collection-like classes that produce values without accepting replacements. section 11.3.3

Passing a herd of cats to a broader API

An invariant Herd<T> rejects feedAll(cats) because Herd<Cat> is not a subtype of Herd<Animal>. Marking the parameter covariant fixes the call: class Herd<out T : Animal> { /* ... */ } fun takeCareOfCats(cats: Herd<Cat>) { for (i in 0..<cats.size) cats[i].cleanLitter() feedAll(cats) } The declaration is safe because Herd exposes T only through operations that produce animals.

Use out when the type parameter appears only in out positions:

  • A covariant class can return T but cannot consume T, preserving type safety. section 11.3.3

Covariant class references

The annotation parameter KClass<out Any> accepts KClass<CompanyImpl>, allowing a concrete class reference to stand in for a reference to any class:

Kotlin declares variance on the class itself, unlike Java's use-site wildcards. The related in modifier reverses subtyping for consumer-like types; out applies to producer-like types. section 11.3.4

How Kotlin in Action, 2E covers it

How deep it goes
Defines preserved subtyping, restricts T to out positions, and contrasts declaration-site variance with Java wildcards.
Examples
Demonstrates Herd<Cat>, List, function types, and KClass<CompanyImpl>.
What it assumes
Assumes generic types, subtype relationships, and basic Kotlin class and function declarations.
What you can do after
Apply it via Kotlin declarations to pass subtype-producing values safely to APIs expecting broader types.
How it connects
Connects covariance with generics, type positions, contravariance, function types, collections, and Java wildcards.

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.