Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 134 ยท Generics and Types

Generics

Learn Kotlin generics: write one function or class that works for many types, use type parameters, upper bounds, nullable type arguments and star projection safely.

Imagine you need a class that holds one value so you can pass it around. You write IntBox for integers, then StringBox for strings, then UserBox, and soon you have a dozen near-identical classes. Or you write one AnyBox that holds Any?, and now every reader of the box must cast the value back to what it "really" is, and the compiler can no longer tell you when you cast wrongly.

Generics solve both problems. You write the class or function once, with a type parameter as a placeholder, and the compiler fills in the real type at every use and checks it. You have been using generics since your first list: List<String> is the generic interface List<E> with String plugged in for E. This lesson shows how to write your own generic functions and classes, how to restrict a type parameter with a bound, how nullability interacts with type parameters, and what a star projection (List<*>) means. The next lessons go deeper: variance, type erasure and reified, and generic constraints.

Generic functions

A type parameter is declared in angle brackets before the function name. By convention it is a single capital letter: T for "type", E for element, K and V for key and value.

Kotlin A function that works for any type

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.

Each call has its own T. In the first call the compiler infers T = Int from the arguments, in the second T = String. You rarely have to write the type yourself, but you can: firstOr<Int>(listOf(1), 0). The explicit form is needed when nothing in the arguments determines T, as with emptyList<Double>() above, where an empty list gives the compiler no hint.

The important point is what the compiler remembers. a is a real Int, not an Any. No cast, no risk. That is the entire value of generics: one implementation, many types, full checking.

Generic classes

Put the type parameter after the class name. Inside the class, T can be used like any other type: in properties, parameters and return types.

Kotlin A generic Stack class

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.

Stack<Int> and Stack<String> are two different types that share one source. The class does not know or care what T is; it only moves values around. When the compiler sees numbers.push("x") it will refuse, because numbers is a Stack<Int>. Try it:

Kotlin The compiler guards the element type (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 error reads main.kt:11:18: error: argument type mismatch: actual type is 'String', but 'Int' was expected. With a plain Any box this mistake would only show up later, at run time, as a ClassCastException in some faraway line. With generics it is caught where you wrote it.

Kotlin often infers the type argument of a constructor too. val names = mutableListOf("a", "b") is a MutableList<String> without you writing <String>. Write the argument explicitly only when the compiler cannot guess, for example Stack<Int>() with no values yet.

More than one type parameter

Separate several parameters with commas. A classic example is a function that builds a pair or a map entry:

Kotlin Two type parameters

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.

Notice how types flow through: swapped() returns an Entry<V, K>, so for an Entry<String, Int> it returns an Entry<Int, String>, and the compiler knows it. A generic function does not need to be inside a generic class: zipToEntries declares its own A and B.

Upper bounds: restricting what T can be

An unrestricted T can be anything, which means inside the function you can do almost nothing with it. You cannot call compareTo on a plain T, because not every type has it. A bound narrows the set of allowed types and, in exchange, lets you use the bound's members. Write the bound after a colon:

Kotlin T must be Comparable

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 : Comparable<T> says "T must be able to compare itself with other Ts". That is what makes item > best legal. Int, String and Double all qualify. A type that does not implement Comparable is rejected at the call:

Kotlin A type without ordering is rejected (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 errors on the second call, starting with type mismatch: inferred type is 'Any', but 'Comparable<Any>' was expected. The wording is clumsy (the compiler tried to find a T for Parcel and gave up), but the meaning is clear: Parcel does not satisfy the bound. The fix is either to make Parcel implement Comparable<Parcel> or to accept a Comparator<T> as a parameter, which is how the standard library's maxWith works. Bounds, multiple bounds and where clauses get a full lesson in Generic Constraints.

Nullability and type parameters

Here is a subtle point that surprises many people: the default upper bound of a type parameter is Any?, not Any. So T can be a nullable type, and then T values may be null.

Kotlin T can be nullable unless you say otherwise

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.

Use T : Any when your function needs a guaranteed non-null value, for example when you store it in a structure where null has a special meaning ("not found"). Our Stack.pop() above returns T?: if T were itself String?, a null result would be ambiguous (empty stack, or a null element?). Declaring class Stack<T : Any> removes the ambiguity. Notice also that you write T? to mean "T or null"; if T is already nullable, T? simply stays nullable.

If you are designing a collection-like class, ask whether null may be an element. If not, write <T : Any>. The standard library's Map<K, V> has V unbounded because null values are legal there, and that is exactly why map[key] returns V? and cannot tell "missing" from "present with null".

Generic extension functions and properties

Extensions can be generic as well, and they are one of the most common uses of the feature. The standard library is full of them (map, filter, firstOrNull are all fun <T> Iterable<T>.something). Writing your own is easy:

Kotlin Your own generic extensions

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 type parameter is declared before the receiver type (fun <T> List<T>.secondOrNull()), and it is inferred from the receiver. See Extension Functions for the extension rules in general and Higher-Order Functions for function parameters like test above.

Star projection: when you do not know the type

Sometimes you hold a collection and truly do not care, or cannot know, what its element type is. Kotlin writes that as *, the star projection: List<*> means "a list of some unknown type".

Kotlin Reading from a List of star

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.

What can you do with a List<*>? You can read elements, but each one has the type Any?, the safest thing the compiler can promise. You can ask for the size, iterate and print. You cannot write a typed element into a MutableList<*>, because the compiler does not know which type is correct, so it forbids all of them (operations that take no element, such as clear(), still work). Star projection is "read-only knowledge" of an unknown type. It is also the only way to name a generic type in an is check, as value is List<*>, which is the topic of Type Erasure and reified.

Kotlin Writing into an unknown list is refused (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.

Reading unknown[0] is fine. The add call fails with receiver type 'MutableList<*>' contains star projection which prohibits the use of 'fun add(element: E): Boolean'. The parameter type of add is effectively Nothing for a star-projected list, so no value fits. This protection is the reason MutableList<*> cannot corrupt the original MutableList<Int>.

Common pitfalls

Generic types are invariant by default. MutableList<Int> is not a MutableList<Any>, even though Int is an Any. If it were, you could add a String through the Any view and break the original. The lesson on variance explains how out and in relax this safely.

You cannot instantiate T. Code such as T() does not compile, because at run time the JVM has no idea what T was. You pass a factory function instead: fun <T> make(create: () -> T): T = create().

You cannot check value is T. The type argument is erased at run time. An inline function with a reified type parameter is the standard workaround; see Type Erasure and reified.

Do not over-generalize. A function with five type parameters and three bounds is usually harder to read than two small functions. Add a type parameter when you actually have two or more types that must relate to each other (the input list and the output element, for instance). If a function only needs "something printable", an interface parameter is simpler than <T : Printable>.

Arrays differ from lists. Array<T> has a fixed element type that is known at run time (on the JVM), unlike List<T>. See Arrays.

When to write your own generic

Write a generic class when it is a container or a wrapper whose logic is independent of its contents (a stack, a cache, a result holder, a tree). Write a generic function when the same algorithm applies to many element types (searching, grouping, retrying). Do not use generics to avoid thinking about a concrete model: a Repository<T> with fun save(item: T) that secretly only works for three types is a design smell. In that case, an interface plus three implementations, or a sealed hierarchy, says what you mean.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of generics over using Any everywhere?

    Generics give you type safety with reuse: the compiler plugs in the real type at each use, so you need no casts. They do not make code faster, they allow null unless you add a bound, and T cannot be instantiated.
  2. 2. What is the default upper bound of a type parameter T?

    An unbounded T is the same as T : Any?, so T may stand for a nullable type. Write T : Any to forbid null.
  3. 3. Which function header lets the body compare two values of type T with the > operator?

    The > operator needs compareTo, which Comparable provides. The bound T : Comparable<T> makes it available. The last form is also invalid syntax, because type parameters come before the function name.
  4. 4. What can you do with a value of type MutableList<*>?

    A star projection means an unknown element type. Reading is safe and returns Any?. Adding a typed value is forbidden because the compiler cannot prove it has the right type. size works fine.
  5. 5. Why is MutableList<Int> not a MutableList<Any>?

    Generic types are invariant by default. If a MutableList<Int> were accepted as MutableList<Any>, adding a String would be legal and the original list would hold a String.

Summary

  • A type parameter (<T>) lets one function or class work for many types; the compiler infers it from the arguments or you write it explicitly.
  • For generic functions the parameter goes before the name (fun <T> name()), for classes after it (class Box<T>).
  • Use a bound (T : Comparable<T>) to be allowed to call the bound's members; the call is rejected for types that do not satisfy it.
  • An unbounded T means T : Any?; write T : Any to exclude null.
  • Extension functions and properties can be generic too.
  • List<*> is a star projection: read as Any?, but no typed writes.
  • Generics are invariant by default, T() and is T do not work, and over-generalizing hurts readability.

Next: Variance: in and out