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:
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
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.
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:
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):
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 |
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 onStringacross a project — keep them close to where they're used, or in a clearly named file likeStringExtensions.kt.
Test yourself
Inside fun String.twice() = this + this, what is this?
- The String class
- The string the function was called on
- The function itself
- null
Can an extension function access private members of the class it extends?
- Yes
- No
- Only in the same file
- 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()?
- The extension
- The member
- Both
- Compile error