Intermediate 8 min readKotlin 2.0
Kotlin Generics — Type-Safe Reusable Code
Generics allow you to write functions and classes that work with any type while preserving type safety at compile time.
What You Will Learn
- Generic functions with <T>
- Generic classes
- Type bounds with where <T : Type>
- Variance: out (covariance) and in (contravariance)
Generic Functions
Add <T> before the function name to make it generic.
Generic Function
kotlin
fun <T> printTwice(value: T) {
println(value)
println(value)
}
fun <T> firstOrNull(list: List<T>): T? {
return if (list.isEmpty()) null else list[0]
}
fun main() {
printTwice("Hello")
printTwice(42)
println(firstOrNull(listOf(10, 20, 30)))
println(firstOrNull<String>(emptyList()))
}Output
Hello
Hello
42
42
10
null
<T> declares a type parameter. T can be any type — the compiler infers it from the argument. firstOrNull returns T? — the type or null.
Beginner Tip: The Kotlin standard library uses generics extensively — List<T>, Map<K,V>, and Optional<T> are all generic types.
Generic Classes
Classes can be generic too.
Generic Class
kotlin
class Box<T>(val value: T) {
fun describe() = "Box containing: $value (${value!!::class.simpleName})"
}
fun main() {
val intBox = Box(42)
val strBox = Box("Kotlin")
println(intBox.describe())
println(strBox.describe())
}Output
Box containing: 42 (Int)
Box containing: Kotlin (String)
Box<T> is a generic class. Each instance fixes T to a specific type. intBox is Box<Int>; strBox is Box<String>.
Type Bounds
Constrain T with an upper bound using : Type.
Type Bounds
kotlin
fun <T : Comparable<T>> max(a: T, b: T): T {
return if (a > b) a else b
}
fun main() {
println(max(3, 7))
println(max("Apple", "Banana"))
println(max(3.14, 2.71))
}Output
7
Banana
3.14
T : Comparable<T> means T must implement Comparable. This allows using > inside the function. Works with Int, String, Double, and any Comparable type.
Practice Exercise
Exercisemultiple choice
What does <T : Number> mean in a generic function?
Quick Quiz
Quick Quiz
What keyword declares a type parameter in Kotlin?
Frequently Asked Questions
Related Tutorials
Last updated: 2026-05-01Kotlin 2.0
Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review