๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Extension Functions

An extension function adds a call to a type without changing the type itself. The new function is called with a dot, just like a member function.

An extension on String

shout is written outside the String type and called on a string value. this inside the body is that string.

fun String.shout(): String {
    return this.uppercase() + "!"
}

fun main() {
    val word = "hello"
    println(word.shout())
}

An extension on Int

squared multiplies the receiver by itself. Even a plain number can stand before the dot as the receiver.

fun Int.squared(): Int {
    return this * this
}

fun main() {
    println(7.squared())
    val n = 5
    println(n.squared())
}

An extension on a list type

total adds up the numbers in the receiver list. The call reads like a member of the list.

fun List<Int>.total(): Int {
    return this.sum()
}

fun main() {
    val prices = listOf(10, 25, 15)
    println(prices.total())
}

The declared type decides

The variable pet is declared as Animal, even though it holds a Dog. The print shows the Animal extension, because the declared type picks the extension.

open class Animal(val name: String)

class Dog(name: String) : Animal(name)

fun Animal.label(): String {
    return "Animal named " + this.name
}

fun Dog.label(): String {
    return "Dog named " + this.name
}

fun main() {
    val pet: Animal = Dog("Rex")
    println(pet.label())
}

Example

fun String.withDots(): String {
    return "..." + this + "..."
}

fun Int.isBig(): Boolean {
    return this >= 100
}

fun main() {
    println("news".withDots())
    println(150.isBig())
    println(40.isBig())
}

Key points

  • Write the type name before the function name to make an extension.
  • The value before the dot is the receiver of the call.
  • Inside the body, this stands for the receiver.
  • An extension can sit on a type from the standard library, such as String or Int.
  • The compiler picks an extension from the declared type of the value.
  • An extension does not replace a member function with the same name.

In this example, withDots wraps its string receiver in dots. The isBig extension compares its number receiver with 100. Both calls use a dot and read like member functions.

Note

Extension functions add calls from outside a class, and they do not change the class.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

Inside an extension function body, what does this stand for?