TExcelTAD
Home › Kotlin › Kotlin Generics

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).

kotlin · try it yourself
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:

kotlin · try it yourself
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":

kotlin · try it yourself
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:

kotlin · try it yourself
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

kotlin · try it yourself
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>
kotlin · try it yourself
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:

kotlin
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?

  1. T must be exactly Comparable
  2. T can be any type that is Comparable to itself
  3. T is optional
  4. T is nullable

Why can a List<Apple> be passed where a List<Fruit> is expected?

  1. Kotlin ignores generics
  2. List is declared with out E (covariant)
  3. Apple is an interface
  4. It can't

How is the type parameter of fun <T> first(list: List<T>): T usually determined?

  1. You must always write it
  2. It is inferred from the argument
  3. It defaults to Any
  4. From the return value