← All courses

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

🗓 May 31, 2026 ⏱ 2 min read

What are scope functions?

Scope functions let you run a block of code on an object without repeating its name. They look similar at first, so the goal of this lesson is to know exactly when to use each one. The difference is two things: how you refer to the object (it or this) and what the block returns (the object or the last line).

FunctionObject isReturnsUse for
letitlast linenull checks, transforms
runthislast linecompute a result
applythisthe objectconfigure an object
alsoitthe objectside effects (logging)
withthislast linegroup calls on one object

let — null checks and transforms

val name: String? = getName()
name?.let {
    println("Hello, $it")   // runs only if name is not null
}

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

apply — configure and return the object

val paint = Paint().apply {
    color = Color.RED        // 'this' is the Paint
    strokeWidth = 4f
    isAntiAlias = true
}   // returns the configured Paint

also — do a side effect, keep the object

val numbers = mutableListOf(1, 2, 3)
    .also { println("Before: $it") }
    .apply { add(4) }
    .also { println("After: $it") }

run and with — group operations

val area = run {
    val w = 4; val h = 5
    w * h                    // returns 20
}

with(user) {
    println(name)            // 'this' is user
    println(email)
}

A practical comparison

// configure (apply) vs transform (let)
val textView = TextView(context).apply {
    text = "Hello"
    textSize = 18f
}

val upper = "hello".let { it.uppercase() }   // "HELLO"

Common mistakes

  • Nesting many scope functions until it/this become confusing — keep it shallow.
  • Using apply when you actually want the computed result (use run/let).
  • Overusing them for trivial code where a plain variable is clearer.
Summary: apply/also return the object (configure / side effects); let/run/with return the last line (transform / compute). Pick by what you need back and whether you prefer it or this.