Generics (Kotlin)

Generics let you write classes and functions that work with any type using type parameters like <T>. Kotlin adds declaration-site variance (in/out) to control how generic types relate as subtypes.

Kotlin

A type parameter <T> is a placeholder filled in at use: class Box<T>(val value: T), fun <T> identity(x: T): T = x. You can constrain it with an upper bound (<T : Comparable<T>>) so the type must support certain operations.

Kotlin's distinctive feature is declaration-site variance. Marking a parameter out (List<out T>) makes it covariant (producer-only), so List<String> is a List<Any>; marking it in makes it contravariant (consumer-only). This solves at the declaration what Java handles awkwardly with wildcards at each use.

For one-off variance you can still use use-site star projections (List<*>) and where clauses for multiple bounds. Reified type parameters on inline functions let you access the type at runtime, which is otherwise erased.

Syntax

class Box<T>(val value: T)
fun <T : Comparable<T>> max(a: T, b: T): T = if (a > b) a else b

Examples

Kotlin

fun <T> firstOrNull(list: List<T>): T? = if (list.isEmpty()) null else list[0]
println(firstOrNull(listOf("a", "b")))
println(firstOrNull(emptyList<Int>()))

Output:

a
null

Learn it in a lesson

See also

Back to the Dictionary