Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 134 ยท Generics and Types

Generic Constraints

Learn Kotlin generic constraints: upper bounds, multiple bounds with where, recursive bounds like Comparable<T>, and definitely non-nullable types written T & Any.

A plain type parameter T is a blank cheque: it can stand for any type, so inside the function you may only do things that every type can do, which is almost nothing (print it, compare it by equals, store it). To say anything useful about T you must tell the compiler what it is guaranteed to have. A constraint (also called a bound) does that: "T is some subtype of Number", "T can compare itself with other Ts", "T is both a CharSequence and Comparable".

You met the simplest form in Generics. This lesson covers the full set: a single upper bound, multiple bounds with where, bounds that refer to other type parameters, the recursive pattern T : Comparable<T>, and the definitely non-nullable type T & Any. Along the way you will see the compiler errors that appear when a bound is violated.

A single upper bound

The bound follows a colon after the type parameter. Everything the bound type offers becomes available on T inside the function, and every caller must pass a type that satisfies it.

Kotlin T must be a Number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Number is the common supertype of Int, Long, Double and the other numeric types. It offers conversion functions such as toDouble(), but no +, so you cannot add two Ts directly: you convert to Double first, as above. If you call the function with something that is not a Number, the compiler refuses:

Kotlin A String is not a Number (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports two errors on the second call: error: cannot infer type for type parameter 'T'. Specify it explicitly. and error: argument type mismatch: actual type is 'List<String>', but 'List<uninferred T (of fun <T : Number> average)>' was expected. The wording is awkward, but the cause is clear: no T can be both a String and within the bound Number. Read it as "the function wants a Number-ish thing and you gave it something else".

Bounds that are your own interfaces

A bound does not have to be a library type. An interface of your own makes generic code capable of something specific:

Kotlin T must have a name

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

This is the real strength of bounds: the function can use name from Named, and it returns the precise type you passed in. If longestName took List<Named> and returned Named, then winner?.age would not compile, because the specific type would be lost. With T : Named the result is a User.

Multiple bounds with where

Sometimes T must satisfy two requirements at once. The colon syntax allows only one bound, so Kotlin offers a where clause that lists all of them:

Kotlin Two bounds on one type parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

T must be both a CharSequence (so .length works) and a Comparable<T> (so minOrNull() works). String is both. The last call in main may surprise you: on the JVM StringBuilder implements Comparable<StringBuilder> since Java 11, so it qualifies, and the result is the smaller one by comparison.

The same syntax works on classes, written after the parameter list:

Kotlin A class with two bounds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Because both bounds hold, Report can sort the rows (Comparable) and render them (Printable). A type that satisfies only one is rejected when you try to construct a Report of it.

Among several upper bounds at most one may be a class; the others must be interfaces, because a type cannot extend two classes. Writing where T : Number, T : String fails with error: only one of the upper bounds can be a class. (plus upper bounds of 'T' have an empty intersection.).

Bounds that refer to other type parameters

A bound may mention another parameter of the same function. This lets you relate types to each other, which is something a single T cannot do.

Kotlin Copying into any compatible collection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

C is some mutable collection that can take T values (the in T is the use-site variance from Variance), and the function returns exactly the collection type the caller passed in: a MutableList<Int> for a list, a MutableSet<Int> for a set. A signature with MutableCollection<T> as the parameter and return type would throw that precision away. The pattern "collection type is a type parameter" appears throughout the standard library (mapTo, filterTo, toCollection).

Recursive bounds: T : Comparable

You have already used T : Comparable<T>. The bound mentions T itself, which reads as "T can compare itself to other Ts". This recursive (or F-bounded) shape is the standard way for a type to express "operations that return my own concrete type". Here it is used to make a fluent builder whose methods keep returning the most specific class:

Kotlin Fluent methods that return the subclass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Without the recursive bound, add would return the base Builder, and .withCheese() after .add("dough") would not compile. Use this pattern sparingly; it is heavy for what it buys. Kotlin offers lighter tools for the same goal: extension functions and scope functions such as apply.

reified types and enums with bounds

Bounds combine naturally with the reified parameters from Type Erasure and reified. A very practical example is a helper that works for any enum:

Kotlin reified plus an Enum bound

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

E : Enum<E> is another recursive bound: "an enum class is an Enum of itself". It makes enumValues<E>() legal. Passing a non-enum type, such as namesOf<String>(), fails to compile because String is not within the bound. You will see enums in depth in Enum Classes.

Definitely non-nullable types: T & Any

We saw that the default bound of T is Any?, so T may be nullable. Writing T : Any forbids a nullable T completely. But what if you want a function that accepts any T, nullable or not, and returns the non-null version of whatever it is given? Kotlin has a special notation for that: T & Any, a definitely non-nullable type.

Kotlin T and Any: removing nullability from a type parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

T here may be String?, Int? or plain String; the result type T & Any is that same type with the question mark stripped, so a String? becomes a String. Compare with T : Any, which would reject nullable arguments entirely. The notation is mostly useful for interoperating with Java's annotations and in library code that must preserve exact types; in everyday application code you need it rarely.

You can only write & with Any on the right. T & Comparable<T> fails with error: intersection types are supported only for definitely non-nullable types: right part must be non-nullable 'Any'. Use a where clause for several requirements.

Choosing a constraint

You want to... Write
Call members of one type on T <T : Bound>
Require two or more capabilities where T : A, T : B
Forbid null <T : Any>
Accept nullable, return non-null T & Any as result type
Compare values of the same type <T : Comparable<T>>
Let a collection type vary but stay exact <T, C : MutableCollection<in T>>
Know the class at run time add inline and reified

If you notice that a constraint has to be repeated on many functions and classes (T : Comparable<T> and T : Printable everywhere), define a small interface that combines them, such as interface Sortable<T> : Comparable<T>, Printable, and use that as a single bound. Your signatures get shorter, and the requirement gets a name.

Common mistakes

Confusing a bound with a parameter type. fun <T : Named> show(x: T) and fun show(x: Named) both accept any Named. They differ when the function returns T or takes two Ts that must match. If neither applies, the plain Named parameter is simpler.

Forgetting that T is invariant. List<T> with T : Number accepts List<Int> because List is covariant, but MutableList<T> does not allow a MutableList<Int> to be treated as a MutableList<Number>. The function simply gets T = Int and you cannot put a Double into the list.

Trying arithmetic on Number. A Number cannot be added to another Number. Convert (toDouble(), toLong()) first, or accept Double/Int and write an overload.

Forgetting that an unbounded T may be null. Member calls on a plain T do not compile for that reason (T could be String?). Use T : Any or a non-null bound such as T : CharSequence when you need members.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does fun <T> maxOf(a: T, b: T) = if (a > b) a else b not compile?

    An unbounded T could be any type, so > is not available. The bound T : Comparable<T> promises compareTo, which the > operator uses.
  2. 2. How do you require that T is both a CharSequence and a Comparable<T>?

    More than one upper bound needs a where clause listing all of them. The colon form takes only one bound, and the ampersand form is only for T & Any.
  3. 3. What does T & Any mean in a result type?

    T & Any is the definitely non-nullable type: for T = String? it is String. It is different from the bound T : Any, which forbids nullable arguments in the first place.
  4. 4. Why is fun <T : Named> longest(items: List<T>): T? often better than fun longest(items: List<Named>): Named?

    With a type parameter the result keeps the caller's exact type, for example User, while the plain version only knows it is Named.
  5. 5. In Builder<SELF : Builder<SELF>>, what is the purpose of the recursive bound?

    The bound ties SELF to the subclass itself, so a fluent method can return SELF and the chain keeps the specific type.

Summary

  • A constraint tells the compiler what a type parameter is guaranteed to offer, so the function body may use those members; callers that break the bound get a compile error.
  • A single upper bound uses a colon: <T : Number>. Several bounds use where T : A, T : B (at most one of them a class).
  • Bounds may refer to other type parameters, as in <T, C : MutableCollection<in T>>, and let you return the exact type passed in.
  • Recursive bounds (T : Comparable<T>, E : Enum<E>, SELF : Builder<SELF>) express "operations on my own type".
  • The default bound is Any?; T : Any forbids nullable arguments, while T & Any is a result type that strips nullability from whatever T is.
  • Prefer a bounded T over a plain supertype parameter only when the result or a second parameter must keep the same precise type.

Next: The Type System Tour