liveBook · Manning

Upper bound

As explained in Kotlin in Action, 2E

An upper bound is a constraint specifying a supertype that every valid substitution for a type parameter must satisfy.

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

How Kotlin in Action, 2E covers it

How deep it goes
Defines syntax, default Any?, multiple bounds, nullability effects, and Java-specific non-null parameters; defers broader generics detail.
Examples
Uses numeric lists, oneHalf, a Comparable max function, multiple bounds, nullable Processor types, and Java-compatible boxes.
What you can do after
Build generic functions and classes that reject invalid type arguments and expose upper-bound operations safely.
How it connects
Connects generic type parameters with subtype constraints, nullability, Comparable, Number, and Java interoperability.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.