Kotlin Generics
Generics let you write classes and functions that work with any type while staying type-safe. List<String> and List<Int> are the same List class, parameterised with different type arguments. The compiler checks every use, so you can't accidentally put an Int into a List<String>.
Generic classes
Declare type parameters in angle brackets after the class name. By convention they're single capital letters: T (type), K/V (key/value), E (element).
class Box<T>(val content: T) {
fun describe() = "Box containing $content"
}
fun main() {
val a = Box("socks") // Box<String>, inferred
val b = Box(42) // Box<Int>
val c: Box<List<Int>> = Box(listOf(1, 2))
println(a.describe())
println(b.content + 8)
println(c.content.size)
}Box containing socks
50
2
Generic functions
Put the type parameter before the function name. The compiler usually infers it from the arguments:
fun <T> repeatToList(item: T, times: Int): List<T> = List(times) { item }
fun <K, V> invert(map: Map<K, V>): Map<V, K> = map.entries.associate { (k, v) -> v to k }
fun main() {
println(repeatToList("ho", 3))
println(repeatToList(7, 2))
println(invert(mapOf("one" to 1, "two" to 2)))
}[ho, ho, ho]
[7, 7]
{1=one, 2=two}
Type constraints
Sometimes your code needs the type to support certain operations. An upper bound <T : Comparable<T>> says "any T that can be compared":
fun <T : Comparable<T>> largest(items: List<T>): T {
var best = items[0]
for (item in items) if (item > best) best = item
return best
}
fun <T : Number> sumAll(values: List<T>): Double = values.sumOf { it.toDouble() }
fun main() {
println(largest(listOf(3, 17, 8)))
println(largest(listOf("pear", "apple", "zucchini")))
println(sumAll(listOf(1, 2.5, 3L)))
}17
zucchini
6.5
Passing a type that doesn't satisfy the bound is a compile error:
fun <T : Number> twice(x: T) = x.toDouble() * 2
fun main() {
println(twice("ten"))
}File.kt:4:13: error: Cannot infer type for type parameter 'T'. Specify it explicitly.
File.kt:4:19: error: Argument type mismatch: actual type is 'String', but 'Number' was expected.
A generic data structure
class Stack<E> {
private val items = mutableListOf<E>()
fun push(item: E) = items.add(item)
fun pop(): E? = items.removeLastOrNull()
fun peek(): E? = items.lastOrNull()
val size get() = items.size
}
fun main() {
val history = Stack<String>()
history.push("home")
history.push("products")
history.push("cart")
println(history.pop())
println(history.peek())
println(history.size)
}cart
products
2
Variance: out and in
Is a List<String> also a List<Any>? For read-only lists, yes — because List is declared List<out E>: it only ever produces E values. A MutableList<String> is not a MutableList<Any>, because you could then add an Int to a list of strings.
| Declaration | Meaning | Example |
|---|---|---|
<out T> |
producer — T only returned | List<out E>, Sequence<out T> |
<in T> |
consumer — T only accepted | Comparator<in T> |
<T> |
both — invariant | MutableList<E> |
open class Fruit(val name: String)
class Apple : Fruit("apple")
fun printAll(fruits: List<Fruit>) = fruits.forEach { println(it.name) }
fun main() {
val apples: List<Apple> = listOf(Apple(), Apple())
printAll(apples) // OK: List is covariant (out)
}apple
apple
Reified type parameters
Generic types are erased at runtime on the JVM, so T::class is normally unavailable. In an inline function you can mark the parameter reified to keep it:
inline fun <reified T> List<Any>.only(): List<T> = filterIsInstance<T>()
listOf(1, "a", 2, "b").only<String>() // [a, b]Tip: Don't make everything generic up front. Write concrete code first; introduce a type parameter when you actually need the same logic for a second type.
Test yourself
What does <T : Comparable<T>> mean?
- T must be exactly Comparable
- T can be any type that is Comparable to itself
- T is optional
- T is nullable
Why can a List<Apple> be passed where a List<Fruit> is expected?
- Kotlin ignores generics
- List is declared with
out E(covariant) - Apple is an interface
- It can't
How is the type parameter of fun <T> first(list: List<T>): T usually determined?
- You must always write it
- It is inferred from the argument
- It defaults to Any
- From the return value