androidengineers.Book a session

Generics and Type Parameters

Type Parameters and where-Constraints

article15 minMedium

Bounds state which operations an algorithm requires

An upper bound permits a generic function to use operations from a particular interface or class. Multiple constraints belong in a where clause.

fun <T> longer(a: T, b: T): T where T : CharSequence, T : Comparable<T> {
    return when {
        a.length > b.length -> a
        b.length > a.length -> b
        else -> if (a >= b) a else b
    }
}

fun main() { check(longer("AI", "Kotlin") == "Kotlin") }

This algorithm needs length and ordering. Without the bounds, those operations are not guaranteed. Constraints are checked at compile time for ordinary Kotlin callers; they do not validate arbitrary external JSON or bypass runtime interoperability concerns.

Avoid adding stronger bounds than the implementation needs. A function that only prints a value does not need a Comparable requirement.

Exercise

Write a generic maximum function for nonempty lists of comparable values. Choose a null-returning alternative for empty input and compare contracts.

Check: explain why bounding every generic type to Any excludes null but does not establish domain validity.

Reference: Upper bounds

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
Type Parameters and where-Constraints | Kotlin Core Programming | Android Engineers