Type constraints
- Kotlin course
- Intermediate
- Lesson 50/116
- 5 min
Learn type constraints with where and upper bounds.
Type constraint
A type constraint forces a generic type parameter to be a subtype of a specific type. Kotlin uses T : UpperBound or the where keyword.
Example: fun <T : Comparable<T>> max(a: T, b: T): T { return if (a > b) a else b }. Here the T : Comparable<T> constraint requires T to be comparable. max(3, 7) works; max(listOf(1), listOf(2)) fails to compile. A type constraint ensures generic functions are called only with suitable types. This prevents runtime errors.
The max function
With a type constraint generic functions can use operators. The T : Comparable<T> constraint enables the > operator.
Example: fun <T : Comparable<T>> max(a: T, b: T): T { return if (a > b) a else b }. Calling max(3, 7) returns 7. Calling max("hello", "world") returns the alphabetically larger one. Thanks to the constraint, the > operator works for any comparable type. The where keyword can express multiple constraints.
Practice The max generic function
Define the generic function fun <T : Comparable<T>> max(a: T, b: T): T whose body returns if (a > b) a else b. In main call println(max(3, 7)).
Starter code
// Define the max generic function
// with a comparable T constraint
// call with two Int values in main and printSample solution
fun <T : Comparable<T>> max(a: T, b: T): T {
return if (a > b) a else b
}
fun main() {
println(max(3, 7))
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the <code>T : Comparable<T></code> constraint provide in a generic function?
- That T is nullable
- That T is a subtype of Comparable<T> Correct answer
- That T is Int
- That T can be any type
Explanation: The T : Comparable<T> constraint requires T to be a subtype of Comparable<T>.
2 Match the type constraint parts
| Term | Meaning |
|---|---|
<T : Comparable<T>> |
Type constraint |
fun max(a: T, b: T) |
Function signature |
: T |
Return type |
a > b |
Comparison |
3 Complete the max function constraint
fun <T : Comparable<____>> max(a: T, b: T): T {
return if (a > b) a else b
}
fun <T : Comparable<T>> max(a: T, b: T): T {
return if (a > b) a else b
}
Explanation: T : Comparable<T> requires T to be comparable.