Generic Classes & Functions in Kotlin
From the Kotlin cheat sheet · Generics · verified Jul 2026
Generic Classes & Functions
Type parameters and constraints
kotlin
// Generic class
class Box<T>(val value: T) {
fun get(): T = value
}
val intBox = Box(42)
val stringBox = Box("Hello")
// Generic function
fun <T> singletonList(item: T): List<T> {
return listOf(item)
}
val list = singletonList("item")
// Multiple type parameters
class Pair<A, B>(val first: A, val second: B) {
fun swap(): Pair<B, A> = Pair(second, first)
}
// Type constraints
fun <T : Comparable<T>> max(a: T, b: T): T {
return if (a > b) a else b
}
// Multiple constraints with where
fun <T> process(value: T)
where T : CharSequence,
T : Comparable<T> {
println("Length: ${value.length}")
println("Value: $value")
}💡 out for covariance (producers), in for contravariance (consumers)
⚡ reified allows using type parameter in is checks
📌 Star projection (*) represents unknown type argument
🟢 Use where clause for multiple type constraints