An upper bound constrains a generic type parameter to a specified type or one of its subtypes. This lets generic code use operations provided by that bound while rejecting incompatible type arguments. section 11.1.3
Kotlin expresses upper bounds directly in the type-parameter declaration:
- Write a colon after the parameter name, as in <T : Number>. section 11.1.3
- Use members of the bound through values of type T; <T : Number> can call Number operations such as toDouble(). section 11.1.3
- Require comparable arguments with <T : Comparable<T>>; incomparable arguments fail at compile time. section 11.1.3
- Add multiple bounds with a where clause, such as T : CharSequence and T : Appendable. section 11.1.3
- Remember that an unconstrained type parameter defaults to Any?, so nullable arguments remain valid. section 7.11 section 11.1.4
Constraining a maximum function
fun <T : Comparable<T>> max(first: T, second: T): T { return if (first > second) first else second } max("kotlin", "java") // kotlin max("kotlin", 42) // compile-time error The bound makes comparison available and prevents mixed, incomparable arguments. section 11.1.3
Listing 11.3 Declaring a function with a type parameter constraint
fun <T: Comparable<T>> max(first: T, second: T): T { #1
return if (first > second) first else second
}
fun main() {
println(max("kotlin", "java"))
// kotlin
}
Browse the complete generic max example, including its declaration, invocation, and result. section 11.1.3
