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.

Create a free account to save this page, take notes and track your progress. Sign in

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.

Extension functions
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.

Extension properties and nullable receivers
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?

  1. Yes, always
  2. No, extensions only see the public API
  3. Only in the same file
  4. Only for data classes
Show answer

Answer: No, extensions only see the public API

Was this page helpful?