Extension Function (Kotlin)

An extension function adds a new method to an existing class without inheriting from it or editing its source. You declare it by prefixing the function name with the receiver type.

Kotlin

fun String.shout() = this.uppercase() + "!" lets you call "hi".shout() as if shout were a built-in String method. Inside the function, this refers to the receiver object. The original class isn't modified — extensions are syntactic sugar resolved statically at the call site.

Extensions are dispatched statically by the declared type, not virtually, so they don't override real methods and a member function always wins over an extension with the same signature. They also can't access private members of the receiver.

They're a cornerstone of idiomatic Kotlin and the Android/Kotlin standard library (apply, let, map, etc. are extensions). Use them to add focused helpers to types you don't own, keeping call sites readable without utility-class clutter.

Syntax

fun ReceiverType.functionName(params): ReturnType { ... }

Examples

Kotlin

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

Output:

true
false

Learn it in a lesson

See also

Back to the Dictionary