Kotlin Tutorial · Object-Oriented Kotlin · Lesson 17 of 31
Kotlin Extension Functions
Add functions and properties to existing types, including ones you don't own, without inheritance.
Extension functions
fun Type.name() adds a function that's called like a member. Inside, this is the receiver. Extensions are
resolved statically (by the declared type) and can't access private members.
fun String.toSlug(): String =
lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-')
fun Int.isEven() = this % 2 == 0
fun main() {
println("Kotlin Coroutines: A Guide!".toSlug())
println((1..6).filter { it.isEven() })
}
Output
kotlin-coroutines-a-guide [2, 4, 6]
Run this on your computer — see “Get Started” for setup.
Extension properties and nullable receivers
Extension properties need a getter (they can't store state). An extension on a nullable type (String?) can be
called on null values.
val String.wordCount: Int
get() = split(" ").count { it.isNotBlank() }
fun String?.orPlaceholder() = if (isNullOrBlank()) "(empty)" else this
fun main() {
println("ship the order today".wordCount)
val missing: String? = null
println(missing.orPlaceholder())
println("Ana".orPlaceholder())
}
Output
4 (empty) Ana
Run this on your computer — see “Get Started” for setup.
Test yourself
Can an extension function access the private members of the class it extends?
Yes, alwaysNo, extensions only see the public APIOnly in the same fileOnly for data classes
Show answer
Answer: No, extensions only see the public API