Kotlin Generic Constraints

A generic type works with any data type, which makes it flexible. Flexibility has a cost: the code knows nothing about the type, so it cannot call useful functions on it. A constraint narrows the choice. The code gains the right to use features that every allowed type guarantees.

The Club Entry Rule

Imagine a gym that accepts any visitor. The staff cannot assume anything about visitors, so they cannot hand out a locker key. A members-only gym works differently. The staff know every member owns a card, and they scan it at the gate. A constraint creates that members-only gate for types.

 Without constraint          With constraint  <T : Comparable<T>>
 -------------------         -----------------------------------
 Any type T enters           +----------------------+
 Nothing is guaranteed       | Gate checks the card |
                             +----------------------+
                              Int      OK
                              String   OK
                              Object   REJECTED

The Problem

This function tries to find the larger of two values:

fun <T> biggest(a: T, b: T): T {
    return if (a > b) a else b   // Error: no comparison for T
}

The compiler refuses. Some types cannot compare with >. A constraint solves the problem.

Upper Bound Syntax

A colon after the type parameter names the required parent type.

fun <T : Comparable<T>> biggest(a: T, b: T): T {
    return if (a > b) a else b
}

fun main() {
    println(biggest(10, 25))          // 25
    println(biggest("apple", "pear")) // pear
    println(biggest(2.5, 1.5))        // 2.5
}

Int, String, and Double all implement Comparable, so each passes the gate. A plain object without that ability fails to compile.

Constraints on Classes

A class can restrict its type parameter as well.

class Box<T : Number>(val value: T) {
    fun doubled(): Double = value.toDouble() * 2
}

fun main() {
    println(Box(21).doubled())     // 42.0
    println(Box(1.5).doubled())    // 3.0
    // Box("text")                 // Error: String is not a Number
}

Every Number offers toDouble(), so the class can call it safely.

Multiple Constraints with where

One type sometimes needs two abilities. The where clause lists them all.

fun <T> shoutLargest(a: T, b: T): String
    where T : CharSequence, T : Comparable<T> {
    val winner = if (a > b) a else b
    return winner.toString().uppercase() + " has " + winner.length + " letters"
}

fun main() {
    println(shoutLargest("kiwi", "mango"))   // MANGO has 5 letters
}

The type must act as text (CharSequence brings length) and support comparison. Strings satisfy both rules.

The Default Bound

A type parameter without a constraint carries the hidden bound Any?. That bound allows null values. A bound of Any blocks null entirely.

class Safe<T : Any>(val item: T)

val ok = Safe("hello")
// val bad = Safe(null)   // Error: null is not allowed

A Practical Example

A sorting helper for any list of comparable items shows the real value of constraints.

fun <T : Comparable<T>> topThree(items: List<T>): List<T> {
    return items.sortedDescending().take(3)
}

fun main() {
    println(topThree(listOf(4, 9, 1, 7, 6)))            // [9, 7, 6]
    println(topThree(listOf("pear", "fig", "apple")))   // [pear, fig, apple]
}

Constraint Summary

SyntaxMeaning
<T>Any type, null allowed
<T : Any>Any type, null blocked
<T : Number>Only number types
<T : Comparable<T>>Only types that compare
where T : A, T : BTypes that satisfy both rules

Tips

  • Choose the weakest constraint that gets the job done.
  • Prefer standard interfaces such as Comparable and Number over custom ones.
  • Read compiler errors about "unresolved reference" on a generic value as a hint that a constraint is missing.