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
fun <T : Comparable<T>> largeraccepts any self-comparable type.- The same body ranks
Ints andStrings; the caller never namesT. firstAndLastreturns aPair<T, T>and destructures cleanly.
Keywords and builtins used here
elsefirstAndLastfuniflargermainval
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.
Step 1 of 3 in Generics & delegation, step 22 of 27 in Language basics.