0Pricing
Kotlin Academy · Lesson

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

  1. Generic Functions and Classes
  2. Declaration-Site Variance
  3. Use-Site Variance
  4. Generic Constraints
← Back to Kotlin Academy