One piece of code for many types
A stack of undo actions and a stack of browser pages need the same code: push, pop, peek. Writing it once for "any element type" without giving up type checks is what generics are for, and you have been using them since the first lesson: List<String>, Map<String, Int> and Pair<A, B> are all generic types.
The interesting questions arise when generic types meet subtyping. A Cat is an Animal; is a list of cats a list of animals? It depends on what you can do with the list. If you can only read from it, yes: everything you take out of a list of cats is certainly an animal. If you can add to it, no: someone holding it as a list of animals could add a dog, and the cat list would be corrupted. Java answers this with wildcards (? extends T, ? super T) written at every use, which most Java developers find hard to read. Kotlin moves the answer to where the type is declared: List is declared as List<out E>, once, and every use benefits. This lesson builds that idea from the ground up, then shows how Kotlin works around the JVM's type erasure with reified type parameters.
Definitions
Definition— Type parameter and bound
class Stack<T> and fun <T> firstNonNull(...) declare type parameters. An upper bound restricts them: <T : Comparable<T>> accepts only types comparable with themselves. Several bounds go in a where clause. Without a bound, T may be nullable; T : Any or the type T & Any excludes null.
Definition— Invariant, covariant, contravariant
Suppose Cat is a subtype of Animal. A generic type G is covariant if G<Cat> is a subtype of G<Animal> (subtyping goes the same way), contravariant if G<Animal> is a subtype of G<Cat> (it goes the opposite way), and invariant if neither holds.
Definition— Declaration-site variance
interface Producer<out T> declares T covariant: T may appear only in "out" positions (return types), never as a parameter type. interface Consumer<in T> declares T contravariant: T may appear only in "in" positions (parameters). The compiler checks these rules.
Definition— Use-site projection and star projection
When a type is invariant, a single use can still be restricted: MutableList<out Animal> is a list you may only read Animals from, and MutableList<in Animal> one you may only put Animals into. List<*> (a star projection) means "a list of some type I do not know"; you can read elements as Any?.
Definition— Reified type parameter
In an inline function, a type parameter marked reified is available at run time: you can write x is T and T::class. This works because the compiler copies the function body into each call site, where the actual type is known.
Generic classes and functions
// A generic class: a stack that works for any element type
class Stack<T> {
private val items = ArrayList<T>()
fun push(item: T) { items.add(item) }
fun pop(): T? = items.removeLastOrNull()
fun peek(): T? = items.lastOrNull()
val size get() = items.size
}
// A generic function with an upper bound: T must be comparable with itself
fun <T : Comparable<T>> clamp(value: T, low: T, high: T): T =
if (value < low) low else if (value > high) high else value
// Several bounds need a where clause
fun <T> lastAlphabetically(items: List<T>): String? where T : CharSequence, T : Comparable<T> =
items.maxOrNull()?.let { "$it (${it.length} chars)" }
// T could be nullable; T & Any (or T : Any) rules that out
fun <T> firstNonNull(vararg candidates: T): T & Any = candidates.firstNotNullOf { it }
// Generic extension function
fun <K, V : Comparable<V>> Map<K, V>.keyOfMax(): K? = entries.maxByOrNull { it.value }?.key
fun main() {
val undo = Stack<String>()
undo.push("type 'hello'")
undo.push("bold")
undo.push("delete line")
println("${undo.pop()} | ${undo.peek()} | size ${undo.size}")
println(clamp(150, 0, 100))
println(clamp(2.5, 0.0, 1.0))
println(clamp("mango", "apple", "kiwi"))
println(lastAlphabetically(listOf("Oslo", "Nairobi", "Lima")))
println(firstNonNull(null, null, "third", "fourth"))
println(mapOf("Accra" to 31, "Oslo" to 4, "Dubai" to 38).keyOfMax())
}delete line | bold | size 2
100
1.0
kiwi
Oslo (4 chars)
third
DubaiStack<T> is checked at every use: undo is a Stack<String>, so undo.push(42) would not compile, and pop() returns String? without a cast. clamp works for integers, doubles and strings because each is Comparable with itself; the < and > operators on T are allowed only because of that bound (they call compareTo). Strings compare alphabetically, so "mango" is clamped to "kiwi".
lastAlphabetically needs T to be both text and comparable, which takes a where clause. firstNonNull returns T & Any, a definitely non-nullable type: whatever T is (here String?, because the arguments include null), the result is the non-null version (String). And keyOfMax is a generic extension: for any map whose values are comparable, return the key of the largest value.
Type arguments are inferred almost everywhere. You write them explicitly when there is nothing to infer from, as in Stack<String>() or emptyList<Int>().
out, in and projections
open class Animal(val name: String) {
override fun toString() = name
}
class Cat(name: String) : Animal(name)
// out: a Producer<Cat> can be used where a Producer<Animal> is expected
interface Producer<out T> {
fun produce(): T
}
// in: a Consumer<Animal> can be used where a Consumer<Cat> is expected
interface Consumer<in T> {
fun consume(item: T)
}
class Shelter : Producer<Cat> {
private var count = 0
override fun produce() = Cat("cat #${++count}")
}
class Vet : Consumer<Animal> {
val seen = mutableListOf<String>()
override fun consume(item: Animal) { seen += item.name }
}
fun adoptAll(from: Producer<Animal>, times: Int): List<Animal> = List(times) { from.produce() }
fun examineCats(cats: List<Cat>, by: Consumer<Cat>) = cats.forEach { by.consume(it) }
// Use-site variance: this function only reads from `from` and only writes Animals into `to`
fun copyInto(from: MutableList<out Animal>, to: MutableList<in Animal>) {
for (a in from) to.add(a)
}
// A star projection: a list of something, we do not care what
fun describe(list: List<*>): String = "${list.size} items, first is ${list.firstOrNull()}"
fun main() {
val cats: List<Cat> = adoptAll(Shelter(), 2).filterIsInstance<Cat>()
println(cats)
val vet = Vet()
examineCats(cats, vet) // a Consumer<Animal> serves as a Consumer<Cat>
println(vet.seen)
val animals: List<Animal> = cats // List is declared List<out E>: covariant
println(animals)
val mutableCats: MutableList<Cat> = mutableListOf(Cat("Tom"))
// val wrong: MutableList<Animal> = mutableCats // does not compile: MutableList is invariant
val everything = mutableListOf<Any>("start")
copyInto(mutableCats, everything)
println(everything)
// Comparator<in T>: a comparator for any object can sort strings
val byText: Comparator<Any> = compareBy { it.toString().length }
println(listOf("kiwi", "fig", "banana").sortedWith(byText))
println(describe(listOf(3, 1, 2)))
println(describe(emptyList<String>()))
}[cat #1, cat #2]
[cat #1, cat #2]
[cat #1, cat #2]
[start, Tom]
[fig, kiwi, banana]
3 items, first is 3
0 items, first is nullCovariance with out. Producer<out T> only ever gives out Ts. A shelter that produces cats can therefore stand in wherever a producer of animals is wanted: everything it produces is an animal. That is why adoptAll(Shelter(), 2) compiles. The compiler enforces the promise: adding fun put(item: T) to Producer fails with "type parameter 'T' is declared as 'out' but occurs in 'in' position".
Contravariance with in. Consumer<in T> only ever takes in Ts. A vet who can examine any animal can certainly examine cats, so a Consumer<Animal> can be passed where a Consumer<Cat> is expected. Subtyping runs backwards, which is exactly what makes it safe.
The standard library uses both. Kotlin's read-only List is declared List<out E>, so val animals: List<Animal> = cats compiles: you cannot add to a read-only list, so nothing can go wrong. MutableList<E> both accepts and returns E, so it must be invariant; the commented-out line fails with "initializer type mismatch: expected 'MutableList<Animal>', actual 'MutableList<Cat>'". The mnemonic is the same as Java's "producer extends, consumer super", spelled in Kotlin as out for producers, in for consumers.
Use-site projections handle invariant types case by case. copyInto takes MutableList<out Animal>, a list it promises only to read, so a MutableList<Cat> is acceptable; and MutableList<in Animal>, a list it promises only to add animals to, so a MutableList<Any> is acceptable. This is exactly Java's ? extends and ? super, with friendlier names.
Java's types are invariant in Kotlin. java.util.Comparator comes from Java, which has no declaration-site variance, so for Kotlin it is invariant: val c: Comparator<String> = Comparator<Any> { ... } does not compile. The standard library compensates with projections in its signatures: sortedWith accepts a Comparator<in T>, which is why sorting strings with a Comparator<Any> works in the program.
Star projections say "some type, unknown". describe can read elements of any list as Any? but could not add to one. Use * when a function genuinely does not care about the element type.
Erasure and reified type parameters
On the JVM, generic type arguments are erased at run time: a List<String> and a List<Int> are both just java.util.List objects. So inside an ordinary generic function, T does not exist when the code runs, and the compiler refuses checks such as x is T ("cannot check for instance of erased type 'T'"). Kotlin offers a way around this for inline functions:
import kotlin.reflect.KClass
import kotlin.reflect.typeOf
// reified: inside an inline function, T is known at run time
inline fun <reified T> List<*>.countOf(): Int = count { it is T }
inline fun <reified T : Any> describeType(): String = "${T::class.simpleName}, type ${typeOf<T>()}"
// A type-safe registry keyed by class: reified type parameters replace Class arguments
class Services {
@PublishedApi internal val byType = mutableMapOf<KClass<*>, Any>()
inline fun <reified T : Any> register(service: T) {
byType[T::class] = service
}
inline fun <reified T : Any> get(): T =
byType[T::class] as? T ?: error("no service registered for ${T::class.simpleName}")
}
class Clock { fun now() = "12:00" }
class Greeter { fun greet(name: String) = "Hello, $name" }
// Without reified, T is erased: the cast below checks nothing at run time
@Suppress("UNCHECKED_CAST")
fun <T> unsafeCast(x: Any): T = x as T
fun main() {
val mixed: List<Any?> = listOf(1, "two", 3.0, "four", null, 5)
println("${mixed.countOf<String>()} strings, ${mixed.countOf<Int>()} ints")
println(mixed.filterIsInstance<Number>()) // the standard library's reified filter
println(describeType<String>())
println(describeType<List<Int>>())
val services = Services()
services.register(Clock())
services.register(Greeter())
println(services.get<Greeter>().greet("Wanjiru") + " at " + services.get<Clock>().now())
try {
services.get<StringBuilder>()
} catch (e: IllegalStateException) {
println(e.message)
}
val numbers: List<String> = unsafeCast(listOf(1, 2, 3)) // no error here: generics are erased
try {
println(numbers.first().length) // the failure surfaces later, elsewhere
} catch (e: ClassCastException) {
println("ClassCastException when the element was used")
}
}2 strings, 2 ints
[1, 3.0, 5]
String, type kotlin.String
List, type kotlin.collections.List<kotlin.Int>
Hello, Wanjiru at 12:00
no service registered for StringBuilder
ClassCastException when the element was usedBecause countOf is inline with a reified T, each call site gets its own copy of the body with the real type substituted: it is String in one place, it is Int in another. The standard library's filterIsInstance<Number>() works the same way. T::class gives the class at run time, and typeOf<T>() (stable since Kotlin 1.6) even preserves type arguments, printing List<Int> in full. The service registry shows a practical use: callers write services.get<Greeter>() instead of passing a class object, and the result is correctly typed.
Two details. A public inline function is copied into callers' code, so it may use only public API; the @PublishedApi internal annotation exposes byType to inlined code without making it part of the public interface. And the last lines show the hazard reified types exist to avoid: unsafeCast "succeeds" in turning a list of integers into a List<String>, because the cast to an erased type checks nothing. The error appears only later, when an element is used as a string, far from the line that caused it. Treat "unchecked cast" warnings as bugs waiting to happen.
Designing a variant type
Example— An outcome type that is easy to use
Suppose a team writes a small type for the outcome of an operation, either a value or an error message:
sealed interface Outcome<out T> {
data class Ok<out T>(val value: T) : Outcome<T>
data class Err(val message: String) : Outcome<Nothing>
}Two choices make it pleasant to use. First, T is declared out: an outcome only ever hands out its value, so an Outcome<Cat> can be returned from a function declared to return Outcome<Animal>, and a list of outcomes of cats is a list of outcomes of animals. Second, Err is an Outcome<Nothing>. Nothing is a subtype of every type, so with covariance an Err is an Outcome<Int>, an Outcome<String>, an outcome of anything: one error class serves all value types, with no type parameter to fill in. The standard library uses the same trick: emptyList() returns a List<Nothing> that fits wherever any list is expected.
Without out, every function returning Outcome<Animal> that had an Outcome<Cat> in hand would need a conversion, and Err would need to be generic too. Variance annotations are a small amount of thought at declaration time that saves every caller from friction later. (Kotlin's standard library has its own Result type for wrapping exceptions; a hand-written sealed type like this is common when errors are part of the domain rather than exceptions.)
Reading and writing generic APIs
- Read signatures with variance in mind. In the standard library,
fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>)says "any comparator that can compareTs or something more general";fun <T> MutableCollection<in T>.addAll(elements: Iterable<T>)says "a collection you may addTs to". Once you can readinandout, library signatures explain themselves. - Declare variance on your own types when they are producers or consumers. A read-only result wrapper, an event source or a parser output should be
out; a handler, validator or sink should bein. It makes your API strictly more flexible for callers, at no cost. - Prefer read-only interfaces in signatures. Accept
List<T>(covariant) rather thanMutableList<T>(invariant) whenever you do not need to modify the argument; callers can then pass a list of a subtype. - Java sees wildcards. When Kotlin code with declaration-site variance is called from Java, the compiler generates Java wildcards in parameter types (a Kotlin parameter
List<Animal>appears to Java asList<? extends Animal>), so Java callers get the same flexibility. The rules are in the Java interoperability documentation. - Do not over-generalise. A generic type parameter that is used once, or a bound nobody needs, adds reading cost without benefit. Make code generic when there are, or soon will be, several concrete types.
Common misconceptions
Misconception
"If Cat is an Animal, a MutableList<Cat> is a MutableList<Animal>." Mutable collections are invariant; otherwise you could add a dog to a list of cats. Read-only List is covariant because it cannot be added to.
Misconception
"out means the value is output-only, so a List<out T> cannot be read." out means the type parameter appears only in output positions of the type's methods, that is, values come out of it. Reading is exactly what you can do.
Misconception
"Reified type parameters remove type erasure in Kotlin." They work only in inline functions, because the body is copied to each call site. Generic classes and non-inline functions are still erased.
Misconception
"Java's Comparator is contravariant in Kotlin, like Consumer<in T>." Java types carry no declaration-site variance, so Kotlin treats them as invariant. Kotlin library functions add in and out projections in their own signatures to make them flexible.
Exercises
1. Generics and variance
CoreHumanWhich of these compile? Choose all that apply.
2. Generics and variance
Warm-upComputationalUsing the lesson's fun <T : Comparable<T>> clamp(value: T, low: T, high: T): T, what does println(clamp(-3, 0, 10) + clamp(42, 0, 10)) print?
3. Generics and variance
CoreComputationalWhat does this program print?
inline fun <reified T> List<*>.countOf(): Int = count { it is T }
fun main() {
println(listOf(1, "a", 2L, 3, 'c').countOf<Int>())
}
4. Generics and variance
CoreHumanWhy does interface Producer<out T> { fun produce(): T; fun put(item: T) } fail to compile?
5. Generics and variance
Warm-upHumanA Validator<T> interface has one method, fun validate(value: T): Boolean. Which variance modifier should its type parameter have, so that a Validator<Any> can be used where a Validator<String> is expected? Give the keyword.
6. Generics and variance
StretchComputationalWhat does this program print?
import kotlin.reflect.typeOf
fun main() {
println(typeOf<Map<String, Int?>>())
}
7. Generics and variance
StretchHumanfun <T> isType(x: Any): Boolean = x is T does not compile ("cannot check for instance of erased type 'T'"). Which change makes the check possible?
Further reading and resources
- Generics: in, out, where (Kotlin documentation) · JetBrainsDeclaration-site variance, type projections, star projections, erasure and reified parameters.
- Inline functions: reified type parameters (Kotlin documentation) · JetBrainsHow reified type parameters work and their limits.
- Calling Java from Kotlin (Kotlin documentation) · JetBrainsHow Java's generic types and wildcards appear in Kotlin.