Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 134 ยท Functions

Extension Functions

Learn Kotlin extension functions and extension properties - receivers, static resolution, nullable receivers, member-wins rule, scope and best practices, with runnable examples.

Sometimes you wish a type had one more method. You would like String to have isPalindrome(), or List<Int> to have secondOrNull(). You cannot edit String (it belongs to the standard library), and inheriting from it is not even possible, because String is final. In Java you would write a static helper such as StringUtils.isPalindrome(s). In Kotlin you write an extension function and call it as if it were a member: s.isPalindrome().

Extensions are one of the features that make Kotlin code read fluently. Most of the standard library you use every day (map, filter, joinToString, lines, trim) is built from extension functions. This lesson shows how to write them, what they can and cannot do, how Kotlin chooses between a member and an extension, and how to use them without making a mess. It builds on Functions and works nicely with Higher-Order Functions.

Writing an extension function

An extension function is a normal function with a receiver type in front of its name. Inside the body, this refers to the object the function is called on:

Kotlin Your first extension functions

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 output is true, true, false, 20 and null. In isPalindrome, this is the string. Like in a member function, you may drop this and just write lowercase() or size: in secondOrNull, size and this[1] are the receiver's members. The receiver type here is String or List<Int>; you can use any type, including generic ones, nullable ones and your own classes.

What an extension really is

Despite the dot syntax, an extension does not modify the class. The compiler turns it into an ordinary static function that receives the receiver as its first parameter. "abc".isPalindrome() compiles to roughly isPalindrome("abc"). This has three consequences you should know:

  1. An extension can only access the receiver's public API. It cannot see private or protected members.
  2. An extension cannot override anything and cannot add state (fields) to the class.
  3. The extension is chosen at compile time based on the declared type of the expression, not the runtime type.

The third point deserves a demonstration.

Extensions are resolved statically

Kotlin Static dispatch of 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.

You get a circle, a shape and a shape. Even though the object is always a Circle, printDescription only knows its parameter as Shape, so the compiler picks Shape.describe. A member function would behave differently (it would be chosen at run time by the actual class). If you need dynamic behaviour, use a member, or an abstract or open member in an interface (see Inheritance), not an extension.

Members win

If a class already has a member function with the same name and compatible parameters, the member always wins, and the extension is never called. IDEs and kotlinc flag such an extension as shadowed:

Kotlin A member shadows an extension

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 output is member greet and extension greet for Ada. The extension without parameters is shadowed by the member; the overload with a different parameter list does not clash, so it works. Remember this rule when you add an extension to a library type: if the library later adds a member with the same signature, your extension quietly stops being used.

Nullable receivers

An extension can be declared on a nullable type. Inside, this may be null, so you handle that case yourself. The standard library does exactly this for isNullOrEmpty() and orEmpty():

Kotlin Extensions on nullable types

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.

You see -, Oslo, -, 42 and <nothing>. Notice that name.orDash() is legal even though name is null: with an ordinary member function that would be a NullPointerException in Java, but an extension is just a static function and can accept null. After the isNullOrBlank() check, this is smart-cast to String, so else this has the right type. See Null Safety for smart casts.

Extension properties

You can also add properties, but only ones without a backing field. They need a custom get() (and optionally set()) because there is nowhere to store a value:

Kotlin Extension properties

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 output is 4, 2, 2, null, Jello and J. A property declared this way looks like a field at the call site (text.wordCount) but runs the getter each time. Because of that, avoid expensive work in an extension getter; a function communicates "this does work" better.

Kotlin An extension property with an initializer (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 main.kt:1:28: error: extension property cannot be initialized because it has no backing field. (plus a second error, 'this' is not defined in this context, for the same spot). Replace the = with get() = ....

Generic extensions and extensions with lambdas

Extensions combine with generics and function parameters, and this is how most of the standard library is built. Here are two small ones in the same style as filter and joinToString:

Kotlin Generic extensions with lambdas

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 prints [a, c, e], 3 and 3. Making the receiver Iterable<T> means the function works for lists, sets, ranges and any other iterable; the more general the receiver type, the more places it applies. The inline keyword (see Inline Functions) avoids creating an object for the lambda.

Where extensions live and how to import them

An extension is a normal top-level declaration, so it belongs to a file and a package. To use an extension from another package you import it by name, just like a function. In a single-file TryIt there is nothing to import, but in a real project it looks like this (a read-only example):

Kotlin
// file: text/Palindromes.kt
package text

fun String.isPalindrome(): Boolean = this == this.reversed()

// file: app/Main.kt
package app

import text.isPalindrome

fun main() {
    println("level".isPalindrome())
}

You can also declare an extension inside a class; it then has two receivers, the extension receiver (the type being extended) and the dispatch receiver (the surrounding class). This is advanced, but the idea is used in DSLs and is introduced in Type-Safe Builders and DSLs:

Kotlin An extension declared inside a 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.

You get 9.50 EUR and 120.00 EUR. Inside Formatter, the extension Double.asMoney can use the class's private currency, which a top-level extension never could. The price is that it only exists inside that class.

Companion object extensions

A class can also gain "static-looking" members by extending its companion object. That only works if the class declares a companion, which is covered in Objects and Companions:

Kotlin Extending a companion object

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 prints 100.0. The empty companion object is what gives you something to extend.

Good practice

  • Name extensions for what they do to the receiver. String.toSlug() reads well; String.process() does not.
  • Keep them near where they matter. An extension used by one file can be private in that file. This avoids polluting auto-complete for everyone.
  • Do not hide heavy work or side effects. An extension that opens files or performs network calls looks like a cheap method, which misleads readers.
  • Prefer a member when you own the class and the function needs private state or polymorphism.
  • Do not overload common names. An extension called get or size on a type that might later get such a member will silently be shadowed.
  • Use the narrowest receiver that works. Declaring on Iterable<T> or CharSequence instead of List<T> or String makes the function reusable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when a class has a member function and you declare an extension with the same name and parameters?

    Members always win over extensions with the same signature, so the extension is shadowed (the compiler warns about it).
  2. 2. Which statement about extension functions is true?

    Extensions are compiled to static functions, so the declared type decides which one is called. They cannot see private members or add state.
  3. 3. Why does val String.shout: String = this.uppercase() not compile?

    There is nowhere to store a value, so an extension property needs a getter such as get() = this.uppercase().
  4. 4. What is true about fun String?.orDash(): String called on a null variable?

    An extension on a nullable receiver is a static function and happily accepts null; inside, you handle the null case yourself.
  5. 5. How do you use an extension function declared in another package?

    Extensions are ordinary top-level declarations, so outside their own package you need import package.name.

Summary

  • fun Receiver.name(...) adds a function you call as value.name(...); inside, this is the receiver.
  • An extension is a static function in disguise: it sees only public members, adds no state and is chosen at compile time.
  • Members win over extensions with the same signature.
  • Receivers can be nullable (String?.orDash()), generic (List<T>.everyOther()) or companion objects.
  • Extension properties need a getter; they cannot be initialized.
  • Import extensions from other packages by name, and keep private helpers private.

Next: Scope Functions