typestar

Generics in Kotlin

Type parameters picked at the call site, bounded where needed.

// T is decided at the call site; the constraint keeps it comparable.
fun <T : Comparable<T>> larger(a: T, b: T): T = if (a >= b) a else b

fun <T> firstAndLast(items: List<T>): Pair<T, T> =
    items.first() to items.last()

fun main() {
    println(larger(1408, 2590))
    println(larger("Brier", "Tolmie"))
    val (start, end) = firstAndLast(listOf("gate", "col", "cirque"))
    println("From the $start to the $end")
}

How it works

  1. fun <T : Comparable<T>> larger accepts any self-comparable type.
  2. The same body ranks Ints and Strings; the caller never names T.
  3. firstAndLast returns a Pair<T, T> and destructures cleanly.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
403
Tokens
134
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 124 seconds.

Type this snippet

Step 1 of 3 in Generics & delegation, step 22 of 27 in Language basics.

← Previous Next →

Generics in other languages