Kotlin Extension Functions (with Examples)

Kotlin course · Functions · Lesson 24 of 51

An extension function lets you add a new function to an existing class, even one you didn’t write, such as String or Int, without changing its code or inheriting from it.

Writing an extension function

Put the type you’re extending (the receiver) before the function name, followed by a dot:

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

fun main() {
    println("Hello".addExclamation())
    println("Kotlin is fun".addExclamation())
}

Output:

Hello!
Kotlin is fun!

Inside the function, this is the value it was called on. You can usually leave this out:

fun String.isValidEmail(): Boolean = contains("@") && contains(".")

fun Int.isEven(): Boolean = this % 2 == 0

fun main() {
    println("asha@example.com".isValidEmail())
    println("not-an-email".isValidEmail())
    println(10.isEven())
    println(7.isEven())
}

Output:

true
false
true
false

Extensions with parameters

fun String.truncate(maxLength: Int, suffix: String = "…"): String =
    if (length <= maxLength) this else take(maxLength) + suffix

fun main() {
    val title = "Kotlin extension functions explained with examples"
    println(title.truncate(20))
    println("Short".truncate(20))
}

Output:

Kotlin extension fun…
Short

Extension properties

You can add properties too, but they can’t store data. They must compute their value:

val String.wordCount: Int
    get() = trim().split(Regex("\\s+")).filter { it.isNotEmpty() }.size

val Int.minutesToHours: String
    get() = "${this / 60}h ${this % 60}m"

fun main() {
    println("Learn Kotlin step by step".wordCount)
    println(135.minutesToHours)
}

Output:

5
2h 15m

Nullable receivers

An extension can be called on a nullable value, and handle null inside:

fun String?.orDash(): String = if (this.isNullOrBlank()) "-" else this

fun main() {
    val a: String? = null
    val b: String? = "Pune"
    println(a.orDash())
    println(b.orDash())
}

Output:

-
Pune

This is how the standard library’s isNullOrEmpty() works.

Extensions on your own classes and lists

data class Product(val name: String, val price: Double)

fun List<Product>.total(): Double = sumOf { it.price }

fun Double.toRupees(): String = "₹" + "%,.2f".format(this)

fun main() {
    val cart = listOf(Product("Mouse", 599.0), Product("Keyboard", 1299.0))
    println(cart.total().toRupees())
}

Output:

₹1,898.00

Real Android examples

These are common in Android projects:

fun View.show() { visibility = View.VISIBLE }
fun View.hide() { visibility = View.GONE }

fun Context.toast(message: String) =
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()

// Usage in an Activity:
// progressBar.hide()
// toast("Saved!")

Android KTX libraries are largely collections of extension functions like these.

How extensions work (and their limits)

  • An extension doesn’t really change the class. Kotlin turns it into a normal function that receives the object as its first parameter.
  • It can only use public members of the class. It can’t access private fields.
  • If the class already has a member function with the same name and parameters, the member wins.
  • Extensions are resolved by the variable’s declared type, not the object’s runtime type.

Where to put extension functions

Put them in a separate file, such as StringExtensions.kt or ViewExtensions.kt, at the top level. Import them where you need them, like any other function.

Common mistakes

  • Trying to store data in an extension property: val String.cache = ... with an initializer doesn’t compile. Use a getter.
  • Using extensions for everything: if a function needs private data, it belongs inside the class.
  • Name clashes: an extension with the same name as a member function is silently ignored.

Exercise

Write an extension Int.toOrdinal() that turns 1 into “1st”, 2 into “2nd”, 3 into “3rd”, 11 into “11th” and so on.

fun Int.toOrdinal(): String {
    val suffix = if (this % 100 in 11..13) "th" else when (this % 10) {
        1 -> "st"
        2 -> "nd"
        3 -> "rd"
        else -> "th"
    }
    return "$this$suffix"
}

fun main() {
    println(listOf(1, 2, 3, 4, 11, 12, 13, 21, 22, 101, 112).map { it.toOrdinal() })
}

Output:

[1st, 2nd, 3rd, 4th, 11th, 12th, 13th, 21st, 22nd, 101st, 112th]

FAQ

What is an extension function in Kotlin?

A function that you add to an existing type from outside, like fun String.shout() = uppercase() + "!", and then call as if it were a member: "hi".shout().

Can extension functions access private members?

No. They can only use the public members of the class.

What happens if an extension has the same name as a member function?

The member function always wins.

WhatsApp us📞 Call now