Kotlin Generics (with Examples)

Kotlin course · Object-oriented programming · Lesson 43 of 51

Updated:

Generics let you write a class or function once and use it with many types, while keeping full type safety. You’ve already used them: List<String>, Map<String, Int> and MutableList<User> are all generic types.

Why generics?

Without generics, a box that can hold any value would have to use Any, and you’d lose type safety:

class AnyBox(val value: Any)
val text = AnyBox("hi").value as String   // manual cast: can crash if wrong

With a type parameter T, the compiler knows exactly what’s inside:

class Box<T>(val value: T) {
    fun describe() = "Box containing $value"
}

fun main() {
    val a = Box("Kotlin")      // Box<String>
    val b = Box(42)            // Box<Int>
    println(a.value.length)    // no cast needed
    println(b.value + 1)
    println(a.describe())
}

Output:

6
43
Box containing Kotlin

T is just a name. You’ll also see K and V for keys and values, E for elements and R for results.

Generic functions

Put the type parameter before the function name:

fun <T> firstOrDefault(items: List<T>, default: T): T =
    if (items.isEmpty()) default else items[0]

fun <K, V> invert(map: Map<K, V>): Map<V, K> =
    map.entries.associate { (k, v) -> v to k }

fun main() {
    println(firstOrDefault(listOf("a", "b"), "none"))
    println(firstOrDefault(emptyList<Int>(), -1))
    println(invert(mapOf("one" to 1, "two" to 2)))
}

Output:

a
-1
{1=one, 2=two}

Kotlin usually works out T from the arguments, so you rarely write it explicitly.

A useful generic class: Result wrapper

sealed class Resource<out T> {
    data class Success<T>(val data: T) : Resource<T>()
    data class Error(val message: String) : Resource<Nothing>()
}

fun loadUserName(id: Int): Resource<String> =
    if (id > 0) Resource.Success("User #$id") else Resource.Error("Invalid id")

fun main() {
    for (id in listOf(7, -1)) {
        when (val r = loadUserName(id)) {
            is Resource.Success -> println("Loaded ${r.data}")
            is Resource.Error -> println("Error: ${r.message}")
        }
    }
}

Output:

Loaded User #7
Error: Invalid id

Constraints: limiting what T can be

Use an upper bound with : to say “T must be this type or a subtype”:

fun <T : Comparable<T>> maxOf3(a: T, b: T, c: T): T {
    var max = a
    if (b > max) max = b
    if (c > max) max = c
    return max
}

fun <T : Number> sumAll(values: List<T>): Double = values.sumOf { it.toDouble() }

fun main() {
    println(maxOf3(4, 9, 2))
    println(maxOf3("pear", "apple", "mango"))
    println(sumAll(listOf(1, 2.5, 3L)))
}

Output:

9
pear
6.5

Because T must be Comparable, b > max compiles. maxOf3(listOf(1), …) wouldn’t.

Variance: out and in

Variance answers the question: if Cat is a subtype of Animal, is Box<Cat> a Box<Animal>?

  • out T (producer): the class only returns T. Then Producer<Cat> can be used as Producer<Animal>. Kotlin’s read-only List<out E> is declared this way, which is why a List<String> can be passed where a List<Any> is expected.
  • in T (consumer): the class only accepts T. Then Consumer<Animal> can be used as Consumer<Cat>.
open class Animal(val name: String)
class Cat(name: String) : Animal(name)

interface Producer<out T> { fun produce(): T }
interface Consumer<in T> { fun consume(item: T) }

fun main() {
    val catShelter: Producer<Cat> = object : Producer<Cat> { override fun produce() = Cat("Kitty") }
    val animalSource: Producer<Animal> = catShelter          // OK thanks to out
    println(animalSource.produce().name)

    val animalVet: Consumer<Animal> = object : Consumer<Animal> {
        override fun consume(item: Animal) = println("Checking ${item.name}")
    }
    val catVet: Consumer<Cat> = animalVet                    // OK thanks to in
    catVet.consume(Cat("Tom"))
}

Output:

Kitty
Checking Tom

A simple rule: if your type only gives T out, mark it out. If it only takes T in, mark it in. If it does both (like MutableList<T>), leave it unmarked.

Star projection: List<*>

Use * when you don’t know or don’t care about the type argument:

fun printSize(list: List<*>) = println("Size: ${list.size}")

fun main() {
    printSize(listOf(1, 2, 3))
    printSize(listOf("a", "b"))
}

Output:

Size: 3
Size: 2

reified: using T at runtime

Normally, the type T is erased at runtime, so you can’t write x is T. In an inline function, mark it reified to keep it:

inline fun <reified T> List<Any>.only(): List<T> = filter { it is T }.map { it as T }

fun main() {
    val mixed: List<Any> = listOf(1, "two", 3.0, "four", 5)
    println(mixed.only<String>())
    println(mixed.only<Int>())
}

Output:

[two, four]
[1, 5]

The standard library’s filterIsInstance<T>() works the same way.

Common mistakes

  • Using Any instead of generics: you lose type safety and need casts.
  • Expecting MutableList<Cat> to be a MutableList<Animal>: it isn’t, because you could add a Dog to it. Read-only List is fine because it’s out.
  • Checking is T without reified: it doesn’t compile. Use an inline function with reified T.

Exercise

Write a generic Cache<K, V> class with put, get and a getOrPut function that computes and stores a value only when it’s missing.

class Cache<K, V> {
    private val store = mutableMapOf<K, V>()
    var misses = 0
        private set

    fun put(key: K, value: V) { store[key] = value }
    fun get(key: K): V? = store[key]

    fun getOrPut(key: K, compute: () -> V): V =
        store[key] ?: compute().also { misses++; store[key] = it }
}

fun main() {
    val squares = Cache<Int, Int>()
    println(squares.getOrPut(12) { 12 * 12 })
    println(squares.getOrPut(12) { 12 * 12 })   // from the cache
    println(squares.getOrPut(5) { 25 })
    println("Computed ${squares.misses} times")

    val names = Cache<String, String>()
    names.put("u1", "Asha")
    println(names.get("u1"))
}

Output:

144
144
25
Computed 2 times
Asha

FAQ

What are generics in Kotlin?

Classes and functions with type parameters, like class Box<T>, so they can work with any type while staying type-safe.

What do in and out mean in Kotlin generics?

out T means the type only produces T (like a read-only list). in T means it only consumes T (like a comparator).

What does reified mean in Kotlin?

In an inline function, reified T keeps the actual type at runtime, so you can use checks like is T or T::class.

WhatsApp us📞 Call now