TExcelTAD
Home › Kotlin › Kotlin Extension Functions

Kotlin Extension Functions

Have you ever wished String had a function it doesn't? In Kotlin you can add one — without inheriting from the class or changing its source. Extension functions let you call your own functions with dot syntax on any type, including types from the standard library or Java.

Declaring an extension

Put the type you're extending (the receiver type) in front of the function name. Inside, this refers to the receiver object:

kotlin · try it yourself
fun String.shout(): String = this.uppercase() + "!"

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

fun main() {
    println("hello".shout())
    println(7.isEven())
    println(10.isEven())
}
HELLO!
false
true

As with members, this. can be omitted: fun String.shout() = uppercase() + "!".

Practical examples

kotlin · try it yourself
fun String.initials(): String =
    split(" ").filter { it.isNotBlank() }.joinToString("") { it.first().uppercase() }

fun Double.format(decimals: Int) = "%.${decimals}f".format(this)

fun List<Int>.secondLargest(): Int? = distinct().sortedDescending().getOrNull(1)

fun main() {
    println("grace brewster hopper".initials())
    println(3.14159.format(2))
    println(listOf(4, 9, 9, 2).secondLargest())
    println(listOf(5).secondLargest())
}
GBH
3.14
4
null

Much of the standard library is built this way: filter, map, joinToString, isNullOrBlank and hundreds more are extension functions.

Extensions on your own classes

Extensions also help keep a class small: the core stays in the class, while convenience functions — perhaps specific to one feature — live elsewhere.

kotlin · try it yourself
data class Temperature(val celsius: Double)

fun Temperature.toFahrenheit() = celsius * 9 / 5 + 32
fun Temperature.feelsLike() = when {
    celsius < 5 -> "cold"
    celsius < 20 -> "mild"
    else -> "warm"
}

fun main() {
    val t = Temperature(23.0)
    println("${t.toFahrenheit()} °F, ${t.feelsLike()}")
}
73.4 °F, warm

Nullable receivers

An extension can be declared on a nullable type and called without a safe call. Inside, check this == null:

kotlin · try it yourself
fun String?.orPlaceholder() = if (this.isNullOrBlank()) "(none)" else this

fun main() {
    val a: String? = null
    val b: String? = "   "
    val c: String? = "Kim"
    println(a.orPlaceholder())
    println(b.orPlaceholder())
    println(c.orPlaceholder())
}
(none)
(none)
Kim

Extension properties

You can add computed properties too (they can't store state, since no backing field is added):

kotlin · try it yourself
val String.wordCount: Int
    get() = trim().split(Regex("\\s+")).count { it.isNotEmpty() }

val <T> List<T>.middle: T?
    get() = if (isEmpty()) null else this[size / 2]

fun main() {
    println("The quick  brown fox".wordCount)
    println(listOf("a", "b", "c", "d", "e").middle)
}
4
c

How extensions work (and their limits)

Extensions are resolved statically: the compiler turns "hi".shout() into a plain call shout("hi"). Consequences:

Fact What it means
no access to private members extensions only see the public API
members win if the class already has a member with the same signature, the member is called
no polymorphism the extension is chosen by the declared type, not the runtime type
need imports an extension in another package must be imported to be used
kotlin · try it yourself
open class Shape
class Circle : Shape()

fun Shape.name() = "shape"
fun Circle.name() = "circle"

fun main() {
    val s: Shape = Circle()
    println(s.name())          // declared type is Shape
    println(Circle().name())
}
shape
circle

Tip: Use extensions to make call sites read naturally (price.toCurrency()), but don't scatter dozens of tiny extensions on String across a project — keep them close to where they're used, or in a clearly named file like StringExtensions.kt.

Test yourself

Inside fun String.twice() = this + this, what is this?

  1. The String class
  2. The string the function was called on
  3. The function itself
  4. null

Can an extension function access private members of the class it extends?

  1. Yes
  2. No
  3. Only in the same file
  4. Only for data classes

If a class has a member fun f() and you declare an extension fun C.f(), which is called by c.f()?

  1. The extension
  2. The member
  3. Both
  4. Compile error