Explain it simply
Generics and extensions in plain language
Generics let one piece of code work for many types while still being checked: a Stack<String> and a Stack<Int> share one class, yet you can never push an Int onto the first. Extension functions let you add a new function to an existing type, even one you did not write, and call it as if it were a member: 'Ada Lovelace'.initials().
Picture a generic as a labelled storage box: the box design is the same, but each box carries a label saying what it holds, and the label is checked every time you put something in or take something out. An extension is a sticker with an extra instruction that you put on someone else's box: the box itself is not changed, you have simply agreed to read the sticker whenever you see that kind of box.
Problem → Why → Solution
The problem: copying a helper for every type
You write a helper that finds the largest value in a list of Ints. A week later you need it for Strings, and then for dates. Copying it three times works until a bug fix has to be repeated in three places. The shortcut, a list of Any, loses the type: the result is an Any you must cast back, and nothing stops a Double from slipping into a list of Strings.
The second pain is utility code. You put fun initialsOf(name: String) in a Utils file, so every call becomes initialsOf(user.name), which reads backwards compared with user.name.initials(). You cannot edit String to add a member, because String belongs to the standard library.
fun largestInt(values: List<Int>): Int? = values.maxOrNull()
fun largestString(values: List<String>): String? = values.maxOrNull()
// "works for everything", but the answer comes back as Any
fun largestAny(values: List<Any>): Any? = values.firstOrNull()
object Utils {
fun initialsOf(name: String) = name.split(" ").map { it.first() }.joinToString("")
}
fun main() {
println(largestInt(listOf(1, 5)))
println(largestAny(listOf(1, "a")))
println(Utils.initialsOf("Ada Lovelace"))
}What type parameters and extensions solve
Type parameters keep the relationship between what goes in and what comes out, so one definition serves every type and the compiler still checks each use. Extension functions solve the second pain without touching the original class: they are ordinary functions whose first parameter is written before the dot, so code reads left to right and IDE completion finds them after the dot.
Core concept: type parameters, bounds and extensions
A type parameter is a placeholder for a type, declared in angle brackets: fun <T> firstOrNull(list: List<T>): T? or class Stack<T>. Every T in the declaration stands for the same type, chosen by the caller. Kotlin usually infers it from the arguments, so largest(listOf(3, 9, 4)) needs no explicit <Int>, while Stack<String>() needs it because there is nothing to infer from. Type parameters exist only at compile time: at run time a List<String> and a List<Int> are both just List, which is called type erasure, and it is why the compiler rejects it is T for a plain T.
An unconstrained T can be anything, so the function body may only do what works for every type. To do more, add an upper bound: <T : Comparable<T>> says 'any T that can be compared with another T'. Now value > best is legal inside the body, and callers can pass Int, String or any Comparable type, but not an Any. Without the bound the same code fails with 'unresolved reference' at the comparison. When a type needs several bounds, use a where clause: where T : CharSequence, T : Comparable<T>.
An extension function is declared with a receiver type in front of the name: fun String.initials(): String. Inside the body this is the receiver, and its members can be used without a prefix, but only public ones; an extension cannot reach private members. The call looks like a member call, "Ada Lovelace".initials(), yet nothing was added to String. The compiler turns it into a static function call and passes the receiver as the first argument. That is why extensions work on nullable types (fun String?.orPlaceholder()) and on classes you cannot edit.
| Feature | Syntax | What it gives |
|---|---|---|
| Generic function | fun <T> name(x: T): T | one definition for many types |
| Upper bound | <T : Comparable<T>> | comparison allowed inside the body |
| Generic class | class Stack<T> | one container, many element types |
| Extension function | fun String.initials() | a member-style call on any type |
| Nullable receiver | fun String?.orPlaceholder() | safe to call even on null |
Because the compiler resolves the call, which extension runs depends on the declared type of the expression, not on the object's runtime type. If Shape and Circle both have an extension named describe, a variable declared as Shape always runs Shape's, even while it holds a Circle. A member function with the same signature always wins over an extension, so an extension can never change existing behaviour; the compiler warns that the extension is shadowed.
- T is a blank the caller fills in
- A bound says what T must support
- An extension is a static function
- The declared type picks the extension
If the compiler says 'unresolved reference' inside a generic body, the usual cure is a bound on T.
General pattern
fun <T> name(param: T): T { ... }
fun <T : Comparable<T>> name(items: List<T>): T? { ... }
class Name<T>(val value: T) { ... }
fun ReceiverType.name(param: Type): Result { ... this ... }
fun <T> Name<T>.name(): List<T> { ... }Declare T before the function name and use it in the parameters and the return type, and add a bound only when the body needs something from T such as comparing or adding. For an extension, write the receiver type before the dot and use it as this inside the body.
Worked example: a Stack<T>, a bounded function and extensions
The program below uses three kinds of tools: a generic class (Stack<T>), a generic function with a bound (largest), and two extensions, one on String and one generic extension on our own class. Predict what it prints before you look, especially the value after size = ...
class Stack<T> {
private val items = mutableListOf<T>()
fun push(item: T) {
items.add(item)
}
fun pop(): T? = items.removeLastOrNull()
val size: Int
get() = items.size
}
fun <T : Comparable<T>> largest(values: List<T>): T? {
var best: T? = null
for (value in values) {
if (best == null || value > best) best = value
}
return best
}
fun String.initials(): String =
split(" ")
.filter { it.isNotBlank() }
.map { it.first().uppercaseChar() }
.joinToString("")
fun <T> Stack<T>.pushAll(vararg values: T) {
for (value in values) push(value)
}
fun main() {
val words = Stack<String>()
words.pushAll("kotlin", "generics", "extensions")
println("size = ${words.size}, top = ${words.pop()}")
println(largest(listOf(3, 9, 4)))
println(largest(listOf("pear", "apple", "zebra")))
println(largest(emptyList<Double>()))
println("Ada Lovelace".initials())
}Code breakdown
- A generic class
class Stack<T> {T is declared on the class, so Stack<String>() and Stack<Int>() share one class while every T means the one type chosen for that stack. push(item: T) refuses any other type.
- T? for an empty stack
fun pop(): T? = items.removeLastOrNull()An empty stack has no top element, so the return type is T?. removeLastOrNull returns null on an empty list instead of throwing, and the type itself tells callers they must handle null.
- An upper bound
fun <T : Comparable<T>> largest(values: List<T>): T? {T : Comparable<T> restricts T to types that can be compared with another T. Int and String qualify, while a list of Any is rejected by the compiler. The return type T? leaves room for null on an empty list.
- Comparing with the bound
if (best == null || value > best) best = valuevalue > best calls compareTo, and it is allowed only because of the bound. After best == null || the compiler knows best is not null (a smart cast), so the comparison needs no ?. at all.
- An extension on String
fun String.initials(): String =String is the receiver, so split(" ") in the body means this.split(" "). The call is "Ada Lovelace".initials() and the result is AL. The String class itself is not modified.
- A generic extension
fun <T> Stack<T>.pushAll(vararg values: T) {An extension can be generic too: T is the same type in the receiver Stack<T> and in the vararg values. The body uses only the public push, so it never touches the private items. The first println shows size = 3 because the string template is evaluated left to right and reads size before pop runs.
size = 3, top = extensions
9
zebra
null
ALExtensions are resolved statically
The sample below shows two facts. First, with val shape: Shape = Circle(), shape.describe() does not call Circle's extension; it calls Shape's, and only Circle() called directly runs Circle's. Second, Greeter's member function hello beats an extension with the same signature.
open class Shape
class Circle : Shape()
fun Shape.describe() = "some shape"
fun Circle.describe() = "a circle"
class Greeter {
fun hello() = "member hello"
}
fun Greeter.hello() = "extension hello"
fun main() {
val shape: Shape = Circle()
println(shape.describe())
println(Circle().describe())
println(Greeter().hello())
}The output is some shape, a circle, member hello. While compiling, the compiler warns 'this extension is shadowed by a member', because the extension can never be called. When behaviour has to differ by runtime type, use an open member function or an interface instead of an extension.
Variance in two minutes: out and in
A String is an Any, but is a List<String> a List<Any>? The answer is yes for List, because it only hands items out (List<out E>), and no for MutableList, because you can put items in. If a MutableList<String> were accepted as a MutableList<Any>, you could add an Int to a list of Strings.
| Declaration | Meaning | Example |
|---|---|---|
| interface Source<out T> | T only comes out; a producer | List<out E> |
| interface Sink<in T> | T only goes in; a consumer | Comparable<in T> |
| class Box<T> | invariant: T goes both ways | MutableList<E> |
interface Source<out T> {
fun next(): T
}
interface Sink<in T> {
fun accept(item: T)
}
fun main() {
val names: List<String> = listOf("Ada", "Linus")
val things: List<Any> = names
println(things)
val editable: MutableList<String> = mutableListOf("Ada")
// val mixed: MutableList<Any> = editable // error: MutableList is invariant
// mixed.add(42) // would put an Int among the Strings
editable.add("Linus")
println(editable)
val source: Source<String> = object : Source<String> {
override fun next() = "hello"
}
val anySource: Source<Any> = source
println(anySource.next())
val printer: Sink<Any> = object : Sink<Any> {
override fun accept(item: Any) = println("got $item")
}
val stringSink: Sink<String> = printer
stringSink.accept("text")
}Uncomment those two lines and the compiler says initializer type mismatch: expected 'MutableList<Any>', actual 'MutableList<String>'. The short rule is out for producers and in for consumers, and most classes you write need neither. Still, knowing why a List<String> can go into a List<Any> parameter makes the error messages easier to read.
In real projects
Where generics and extensions show up in real projects
The standard library is built from generics and extensions. List<T>, Map<K, V>, Result<T> and Sequence<T> are generic types, while map, filter and joinToString are extension functions on Iterable<T>, which is why you can call them on any collection. In application code, a Repository<T> or a generic ApiResult<T> hides plumbing that would otherwise be written again and again, and extensions such as String.toSlug() or Double.toMoney() turn repeated conversions into readable calls. Libraries such as Android KTX add extension functions to framework classes.
Keep an extension close to where it is used, in the same file or module and preferably private, so that it cannot clash with another library's. And do not make everything generic: if only one concrete type is ever used, a plain type is clearer.
Common mistakes
Common mistakes with generics and extensions
Expecting an extension to behave like an override
Write one extension for Shape and one for Circle, put a Circle in a Shape variable, and Shape's extension runs; this is not polymorphism. When behaviour has to follow the runtime type, use a member function (open and override) or an interface, and keep extensions for helpers.
Comparing values of an unbounded T
fun <T> biggest(a: T, b: T) = if (a > b) a else b does not compile; the compiler says 'unresolved reference. None of the following candidates is applicable because of a receiver type mismatch', since T could be a type that cannot be compared. Add <T : Comparable<T>> rather than patching it with a cast or Any.
Assuming an extension can reach private members
For class Account(private val pin: String), fun Account.check() = pin.length fails with the error cannot access 'val pin: String': it is private in '/Account', because an extension is just a function outside the class. Keep logic that needs private state inside the class, or expose what it needs as a public member.
Best practices
Best practices
- Add a bound to a type parameter only when the body needs it, and name several parameters by role: K and V, or TItem.
- Write small, stateless helpers as extensions, and keep behaviour that needs private state inside the class itself.
- Declare an extension in the file or module that uses it (private fun) so it cannot clash with another library's.
- Members always win, so when the type already has a method with that name, give the extension a different name.
Mini challenge
Mini challenge: Box, isSortedAscending and toTitleCase
Add three small tools: a generic class Box<T> that holds a value and has a map function returning a Box<R>; an extension on List that reports whether a list of Comparable values is sorted ascending; and an extension on String that turns 'hELLO kotlin' into 'Hello Kotlin'.
- Box<T> has val value and fun <R> map(transform: (T) -> R): Box<R>
- isSortedAscending is an extension on List<T> with the bound T : Comparable<T>, and returns true for an empty list
- toTitleCase copes with extra spaces between words and capitalises the first letter of each word
- Print Box(21).map { it * 2 }.map { "answer: $it" }, and call the other two functions as well
// TODO: a generic class that holds a value; map returns a Box of the new type
class Box<T>(val value: T) {
// TODO: fun <R> map(transform: (T) -> R): Box<R>
}
// TODO: make this generic with a bound so any Comparable element type works
fun List<Int>.isSortedAscending(): Boolean {
TODO()
}
// TODO: lower-case every word, then upper-case its first letter
fun String.toTitleCase(): String {
TODO()
}
fun main() {
// TODO: build Box(21), map to double it, then map to "answer: <value>", print value
// TODO: print isSortedAscending for a sorted Int list, an unsorted String list
// and an empty list
// TODO: print " hELLO kotlin wORLD ".toTitleCase()
}Expected: It prints answer: 42, then true, false, true, and finally Hello Kotlin World.
Show hint
In Box.map, return Box(transform(value)). For isSortedAscending, loop from index 1 up to size and return false when this[i - 1] > this[i]. For toTitleCase, chain split(" ") into filter { it.isNotEmpty() } and finish with joinToString(" ").
Show solution
class Box<T>(val value: T) {
fun <R> map(transform: (T) -> R): Box<R> = Box(transform(value))
}
fun <T : Comparable<T>> List<T>.isSortedAscending(): Boolean {
for (i in 1 until size) {
if (this[i - 1] > this[i]) return false
}
return true
}
fun String.toTitleCase(): String =
split(" ")
.filter { it.isNotEmpty() }
.joinToString(" ") { word ->
word.lowercase().replaceFirstChar { it.uppercase() }
}
fun main() {
val box = Box(21).map { it * 2 }.map { "answer: $it" }
println(box.value)
println(listOf(1, 2, 2, 5).isSortedAscending())
println(listOf("b", "a").isSortedAscending())
println(emptyList<Int>().isSortedAscending())
println(" hELLO kotlin wORLD ".toTitleCase())
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- <T> is a type blank the caller fills in, usually by inference, and it is erased at run time.
- A bound such as T : Comparable<T> decides what the body may do with T, and without it you get unresolved reference.
- An extension is a static function chosen by the declared type; it never beats a member and cannot reach private members.
- List<out E> may be used as a List<Any>, but MutableList is invariant, so MutableList<String> is not a MutableList<Any>.
Kotlin language guide — Kotlin