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
