Scope Functions (let, run, with, apply, also) (Kotlin)

Scope functions run a block of code in the context of an object. let, run, with, apply, and also differ in how they refer to the object (it vs this) and what they return (the result vs the object).

Kotlin

All five execute a lambda on an object but with different conventions. apply and also return the object itself (good for configuring and chaining); let, run, and with return the lambda's result. Inside apply/run/with the object is this; inside let/also it's it.

Common idioms: let for null-safe operations (value?.let { ... }) and transforming a value into another; apply for building/configuring an object (Person().apply { name = "Ana" }); also for side effects like logging without breaking a chain; run for executing a block and computing a result; with for grouping calls on a known object.

They overlap, so pick by the two questions: do you want it or this, and do you want the object back or the lambda's result? Choosing the conventional one keeps code readable, but over-nesting scope functions hurts clarity.

Syntax

obj.let { it -> result }
obj.apply { this.config = ... }  // returns obj

Examples

Kotlin

data class Person(var name: String = "", var age: Int = 0)
val p = Person().apply {
    name = "Ada"
    age = 36
}
println(p)
val upper = "hi".let { it.uppercase() }
println(upper)

Output:

Person(name=Ada, age=36)
HI

Learn it in a lesson

See also

Back to the Dictionary