Kotlin

Generic Class and Function

admin by @admin ADMIN
Jun 12, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`<T>` declares a type parameter. Use it on classes (`Box<T>`) and functions (`fun <T> identity(x: T) = x`). Type bounds (`T : Comparable<T>`) constrain what T can be.
Kotlin
Raw
class Box<T>(val value: T) {
    fun <U> map(f: (T) -> U): Box<U> = Box(f(value))
}

// Generic function with a type bound
fun <T : Comparable<T>> max(list: List<T>): T {
    var best = list[0]
    for (item in list) if (item > best) best = item
    return best
}

// Multiple bounds via `where`
fun <T> copyIfNotNull(src: T?, dst: T)
    where T : Cloneable, T : java.io.Serializable {
    /* ... */
}

fun main() {
    val intBox: Box<Int>    = Box(42)
    val strBox: Box<String> = intBox.map { it.toString() }
    println(strBox.value)                                // "42"

    println(max(listOf(3, 1, 4, 1, 5, 9, 2)))           // 9
    println(max(listOf("apple", "banana", "cherry")))    // "cherry"
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.