Kotlin · Module 6 · Lesson 11 min read

Extension & Scope Functions

Extension functions

Add new functions to existing classes, even ones you don't own:

kotlin
fun String.isEmail() = contains("@") && contains(".")
"ana@mail.com".isEmail()     // true

val Int.minutes get() = this * 60   // extension property

They don't really change the class; it's neat syntax for a function taking the receiver. They're used everywhere in Android KTX: view.isVisible = true, context.toast("Hi").

Scope functions

They run a block of code on an object, and differ in how you refer to the object and what they return:

FunctionObject inside asReturnsTypical use
letitthe lambda resultnull checks: x?.let { … }, transforming
runthisthe lambda resultcompute a result with the object
with(obj)thisthe lambda resultseveral calls on one object
applythisthe objectconfiguring a new object
alsoitthe objectside effects such as logging and validation
kotlin
val user = User().apply {
    name = "Ana"
    age = 20
}.also { println("Created $it") }

val length = name?.let { it.trim().length } ?: 0

Choosing quickly

  • Building or configuring something → apply.
  • Doing something extra without changing the result → also.
  • Working with a nullable value → ?.let.
  • Calculating a value from an object → run / with.

⚠️ Don't nest them deeply; readability comes first.

Example

kotlin
fun String.isEmail() = contains("@") && substringAfter("@").contains(".")
fun String.initials() = split(" ").filter { it.isNotBlank() }.joinToString("") { it.first().uppercase() }
val Int.minutes get() = this * 60
fun <T> List<T>.second(): T? = getOrNull(1)

class Profile {
    var name = ""
    var age = 0
    var skills = mutableListOf<String>()
    override fun toString() = "Profile($name, $age, $skills)"
}

fun main() {
    println("ana@mail.com".isEmail())
    println("not-an-email".isEmail())
    println("Asha Kumari Rai".initials())          // AKR
    println("25 minutes = ${25.minutes} seconds")
    println(listOf("a", "b", "c").second())

    val profile = Profile().apply {                  // configure → returns the object
        name = "Ana"
        age = 20
        skills += "Kotlin"
    }.also { println("Created: $it") }               // side effect → returns the object

    val nickname: String? = "  annie  "
    val len = nickname?.let { it.trim().length } ?: 0
    println("Nickname length: $len")

    val summary = with(profile) { "$name knows ${skills.size} skill(s)" }
    println(summary)
    val isAdult = profile.run { age >= 18 }
    println("Adult? $isAdult")
}