Kotlin Scope Functions: let, run, with, apply and also

Kotlin course · Functions · Lesson 25 of 51

Kotlin’s standard library has five scope functions: let, run, with, apply and also. Each one runs a block of code on an object. They differ in two ways: how you refer to the object inside the block (it or this), and what the block returns.

Quick comparison

FunctionObject inside the blockReturnsTypical use
letitthe lambda resultrun code on a non-null value: x?.let { }
runthisthe lambda resultcompute a value using an object
withthisthe lambda resultcall several functions on one object
applythisthe object itselfconfigure a new object
alsoitthe object itselfdo something extra (log, validate)

We’ll use this class in the examples:

data class User(var name: String, var age: Int = 0, var email: String = "")

let

let is most often used with ?. to run code only when a value isn’t null. It returns the result of the block:

fun main() {
    val email: String? = "asha@example.com"
    val domain = email?.let { it.substringAfter("@") }
    println(domain)

    val missing: String? = null
    val length = missing?.let { it.length } ?: 0
    println(length)
}

Output:

example.com
0

apply

apply is used to configure an object. Inside the block, this is the object, so you can set properties directly. It returns the object itself:

data class User(var name: String, var age: Int = 0, var email: String = "")

fun main() {
    val user = User("Ravi").apply {
        age = 29
        email = "ravi@example.com"
    }
    println(user)
}

Output:

User(name=Ravi, age=29, email=ravi@example.com)

In Android, you’ll see apply used to set up Intents, Bundles, Paint objects and views.

also

also gives you the object as it and returns the object unchanged. Use it for side effects such as logging or validation, without breaking a chain:

fun main() {
    val numbers = mutableListOf(3, 1, 2)
        .also { println("Before sorting: $it") }
        .apply { sort() }
        .also { println("After sorting: $it") }
    println(numbers.size)
}

Output:

Before sorting: [3, 1, 2]
After sorting: [1, 2, 3]
3

run

run uses this and returns the block’s result. It’s handy when you configure something and compute a result in one go:

data class User(var name: String, var age: Int = 0, var email: String = "")

fun main() {
    val user = User("Meera", 31, "meera@example.com")
    val summary = user.run {
        "$name ($age) – ${email.substringAfter("@")}"
    }
    println(summary)
}

Output:

Meera (31) – example.com

with

with is like run, but it isn’t an extension: you pass the object as an argument. Use it to call several functions on the same object:

fun main() {
    val sb = StringBuilder()
    val text = with(sb) {
        append("Kotlin ")
        append("scope ")
        append("functions")
        toString()
    }
    println(text)
}

Output:

Kotlin scope functions

it vs this

  • it (let, also): good when you pass the object to other functions or want a clear name: user.let { save(it) }. You can rename it: user.let { u -> save(u) }.
  • this (run, with, apply): good when you mostly call the object’s own members, because you can leave this. out.

How to choose

  1. Is the value nullable and you want to run code only when it isn’t? → ?.let
  2. Are you configuring a new object? → apply
  3. Do you want to do something extra and keep the object? → also
  4. Do you need to compute a result from an object? → run (or with if it isn’t nullable and you prefer that style)

All five side by side

data class User(var name: String, var age: Int = 0, var email: String = "")

fun main() {
    val u = User("Zoya", 22)

    val a = u.let { it.name.length }        // Int: 4
    val b = u.run { age + 1 }               // Int: 23
    val c = with(u) { "$name is $age" }     // String
    val d = u.apply { email = "z@x.com" }   // User (same object)
    val e = u.also { println("Log: ${it.name}") }  // User (same object)

    println(a)
    println(b)
    println(c)
    println(d)
    println(d === e)
}

Output:

Log: Zoya
4
23
Zoya is 22
User(name=Zoya, age=22, email=z@x.com)
true

Common mistakes

  • Nesting scope functions: a.let { b.apply { c.also { } } } quickly becomes unreadable. Use local variables instead.
  • Using apply when you need a result: apply always returns the object, not the last line.
  • Shadowing it: nested lets each have their own it. Name the parameters to avoid confusion.

Exercise

Create a User with apply, log it with also, and use let to safely print the email domain only if the email isn’t blank.

data class User(var name: String, var age: Int = 0, var email: String = "")

fun main() {
    val user = User("Kabir")
        .apply {
            age = 26
            email = "kabir@techpass.dev"
        }
        .also { println("Created: $it") }

    user.email.takeIf { it.isNotBlank() }?.let {
        println("Domain: ${it.substringAfter("@")}")
    }
}

Output:

Created: User(name=Kabir, age=26, email=kabir@techpass.dev)
Domain: techpass.dev

FAQ

What is the difference between let and apply in Kotlin?

let gives you the object as it and returns the block’s result. apply gives you the object as this and returns the object itself.

What is the difference between apply and also?

Both return the object. apply uses this (for configuring), also uses it (for side effects like logging).

When should I use with in Kotlin?

When you want to call several functions on an object that isn’t null and you don’t need the object returned, like building a string with a StringBuilder.

WhatsApp us📞 Call now