Generic Constraints
Bound type parameters.
Constraining Type Parameters
Sometimes a generic must accept only certain types, for example types that are comparable or that subclass a base. Generic constraints set an upper bound on a type parameter.
The Default Upper Bound
Without a constraint, a type parameter's upper bound is Any?, so it accepts any type including nullable ones. To allow only non-null types, bound it to Any.
fun <T : Any> requireNonNull(value: T): T {
return value
}
fun main() {
println(requireNonNull(42))
}All lessons in this course
- Generic Functions and Classes
- Declaration-Site Variance
- Use-Site Variance
- Generic Constraints