An extension function is declared with a receiver type before the function name, and is then called as though it were a method on that type. You can extend String, List, or any class from a library you cannot modify. Most of Kotlin's own standard library is written this way - List.map is an extension, not a member.
Nothing is actually added to the class. The compiler turns an extension into a static function taking the receiver as its first parameter, which has two consequences worth knowing. Extensions are resolved statically, by the declared type of the expression rather than its runtime type, so they do not participate in polymorphism. And a member function always wins over an extension with the same signature - you cannot override behaviour by extending.
Extensions can be declared on nullable types, which is how isNullOrEmpty works: the receiver inside is String? and the function handles null itself rather than requiring the caller to.
A function literal with receiver - a lambda where this is bound to an object - is the mechanism behind every Kotlin DSL, including the apply scope function and the whole of Jetpack Compose. The buildString example below shows the shape.
// An extension on a type we do not own
fun String.initials(): String =
split(" ").filter { it.isNotEmpty() }.joinToString("") { it.first().uppercase() }
// An extension on a nullable receiver, handling null itself
fun String?.orPlaceholder(): String = if (this.isNullOrBlank()) "unknown" else this
// An extension on a generic type
fun <T> List<T>.second(): T? = if (size >= 2) this[1] else null
fun main() {
println("Ada Lovelace".initials()) // AL
println(null.orPlaceholder()) // unknown
println(listOf("a", "b", "c").second()) // b
// A lambda with receiver: this is the StringBuilder inside the block
val report = buildString {
appendLine("Report")
appendLine("------")
append("done")
}
println(report)
}
Discussion
No questions on this topic yet. Sign in to ask the first one.