Scope functions

Learn Kotlin scope functions for Android to master how they pass objects and return values, avoiding silent bugs and improving code readability. About 22 minutes.

Why it matters

  • Scope functions appear in nearly every Kotlin codebase. Swapping apply for let or run silently changes what the expression returns.
  • Interviewers ask you to refactor a null-check chain or a builder block and explain why each function was chosen.
  • Chained scope calls hide control flow. Reviewers and on-call engineers need to read them quickly during incident triage.
  • Knowing when NOT to use a scope function (long lambdas, nested chains) is the difference between idiomatic Kotlin and code that needs a second pass to understand.

The simple explanation

  • Imagine a workshop bench. You bring a tool (the object) and do work on it.
  • apply is like fixing the tool and handing it back to you. You get the tool, not the wrench you used.
  • also is like asking a colleague to inspect the tool while you keep working. You still hold the tool.
  • let is like handing the tool to a specialist who gives you a new product. You get the result, not the original tool.
  • with is like saying "work on this tool" without naming it on every line.
  • run is a blank workbench: you do a sequence of steps and hand over the last item on the bench.

Kotlin provides five scope functions: let, run, with, apply, also. They differ on two axes: how the object enters the lambda (this or it) and what the expression returns.

FunctionObject in the lambdaReturns
letitlambda's last expression
runthis (no object for the plain run { } form)lambda's last expression
withthis (passed as an argument)lambda's last expression
applythisthe object itself
alsoitthe object itself

The critical split: let, run, with return the lambda result; apply and also return the object. This is the distinction that matters most.

let is the standard null-check idiom: x?.let { transform(it) } ?: fallback. apply configures a mutable object and hands it back, so the last expression inside is ignored. also adds a side-effect such as logging or validation without altering the pipeline. with avoids repeating an object's name inside a block. run groups a sequence of expressions, with or without an object.

Do not use scope functions just to avoid a local variable. If the lambda body grows long, a named val is usually clearer. Chaining three or more scope calls is harder to read than a sequence of statements. Swapping apply or also for let, run or with changes the result from the object to the lambda's value, which can be a compile error or a wrong value at runtime.

Notes

  • All five work on any type, including nullable ones. let, run, apply and also are extension functions on a generic T. with is a normal top-level function that takes the object as its first argument: with(obj) { }.
  • To skip the block when the value is null, use a safe call: x?.let { }, x?.apply { }. Without ?. the block runs and the object inside is still nullable.
  • apply and also return the object, not the lambda's last expression. The last expression inside an apply or also block is ignored.
  • x?.let { ... } ?: default is the idiomatic null-check. Inside the lambda, it has the non-null type.
  • Watch out: in x?.let { ... } ?: default the default also runs when the lambda itself returns null, not only when x is null.
  • run has two forms: obj.run { } (extension, this is the object) and run { } (top-level, no object, just a block that returns its last expression).
  • with is not an extension, so you cannot write obj?.with { }. If the object may be null, this inside with is nullable. Prefer obj?.run { } in that case.
  • also passes the object as the it parameter. Inside also, this still means the outer class, so you write it.property. Inside apply, a bare name means the object's name.
  • Chaining apply then also keeps the type, because both return the object. Chaining apply then let changes the type to whatever the let lambda returns.
  • Scope functions are for short, single-purpose blocks. When a lambda grows long, replace it with a local val and plain statements.
  • All five are inline functions in the standard library. The lambda body is copied into the call site, so no lambda object is created and there is no runtime cost.
  • also is the right choice for logging or validation side-effects in a pipeline because it returns the original object, keeping the chain type-stable.

Code example

This sample shows all five scope functions in a small data-processing pipeline: null-safe parsing with let, configuring a builder with apply, side-effect logging with also, object shorthand with with, and expression grouping with run.

// Scope functions in a data-processing pipeline
 
// 1. let: null-safe transform, returns lambda result
fun parsePort(raw: String?): Int {
    return raw?.let {
        val trimmed = it.trim()
        val port = trimmed.toIntOrNull()
        if (port == null || port !in 1..65535) -1 else port
    } ?: -1
}
 
// 2. apply: configure a mutable object, returns the object itself
fun buildQuery(params: Map<String, String>): String =
    StringBuilder().apply {
        append("/api/v1/items?")
        params.entries.forEachIndexed { index, (key, value) ->
            if (index > 0) append("&")
            append(key + "=" + value)
        }
    }.toString()   // apply returned the StringBuilder, so convert it here
 
// 3. also: side-effect without changing the pipeline type
fun loadAndLog(data: List<String>): List<String> {
    return data.also {
        println("Loaded " + it.size + " items")
    }.filter { it.isNotBlank() }
}
 
// 4. with: operate on an object without repeating its name
fun summarize(stats: Map<String, Int>): String {
    return with(stats) {
        val total = values.sum()
        val max = values.maxOrNull() ?: 0
        "total=" + total + " max=" + max
    }
}
 
// 5. run: no-object block, returns the last expression
fun process(input: String): Int = run {
    val cleaned = input.trim().lowercase()
    val words = cleaned.split(" ").filter { it.isNotEmpty() }
    words.size
}
  • parsePort uses let after a safe call, so the null case is handled by ?: -1 without a separate if block. Here the lambda never returns null, so the fallback runs only for a null input.
  • buildQuery uses apply on a StringBuilder. apply returns the StringBuilder itself, so the function calls toString() on the result. A Map has no forEachIndexed, so the code iterates over params.entries. The standard library's buildString { } does the same job in one call.
  • loadAndLog chains also then filter. also returns the original List<String>, so filter receives the right type. Swapping also for let would break the chain: let returns the lambda result, here Unit from println, so filter would not compile.
  • summarize uses with to avoid writing stats.values twice. Inside the block, values means stats.values.

Run the idea in plain Kotlin

fun main() {
  // let: null-safe transform
  val raw: String? = "  8080  "
  val port = raw?.let {
      val p = it.trim().toIntOrNull()
      if (p != null && p in 1..65535) p else -1
  } ?: -1
  println("let result: " + port)

  // apply: returns the receiver, not the lambda result
  val sb = StringBuilder()
  sb.apply {
      append("hello")
      append(" world")
  }
  println("apply result: " + sb.toString())

  // also: side-effect, returns the receiver
  val numbers = listOf(1, 2, 3, 4, 5)
  val evens = numbers.also {
      println("also: original size = " + it.size)
  }.filter { it % 2 == 0 }
  println("also result: " + evens)

  // with: object passed as an argument
  val scores = mapOf("a" to 10, "b" to 20, "c" to 30)
  val total = with(scores) {
      values.sum()
  }
  println("with result: " + total)

  // run: no-receiver block, returns last expression
  val wordCount = run {
      val s = "  hello world foo  "
      val words = s.trim().split(" ").filter { it.isNotEmpty() }
      words.size
  }
  println("run result: " + wordCount)
}

In production

Wrong return type after swapping apply for run
  • A module built its config with fun defaultConfig() = Config().apply { retries = 3 }. The return type was not written, so the compiler inferred it.
  • In a refactor someone changed apply to run to match the style of the rest of the file.
  • run returns the lambda's last expression. The last line was an assignment, so the lambda returned Unit and defaultConfig() now returned Unit instead of Config.
  • The only caller passed the result to a service locator that accepted Any, so everything still compiled. The app crashed at startup with a ClassCastException when the config was read back as Config.
The fix
  • Reproduce with a unit test that reads the config from the locator. It fails before the fix.
  • Revert to apply, because the intent was to configure and return the object, not to compute a new value.
  • Declare return types on public functions: fun defaultConfig(): Config. Now the wrong scope function is a compile error. In library modules, Kotlin's explicit API mode makes declared return types mandatory for public API.
  • Add a code-review rule: "When changing a scope function, check what the expression returns."
The login screen that opened for logged-in users
  • A screen used session?.let { restoreDraft(it.userId) } ?: run { navigateToLogin() }.
  • restoreDraft returns Draft?: null when the user has no saved draft.
  • The ?: runs its right side whenever the left side is null. That happens when session is null, but also when the let lambda returns null.
  • Logged-in users with no saved draft were sent to the login screen. There was no crash and no error log, only confused users.
The fix
  • Reproduce with a unit test: a valid session and no draft. Assert that login is not opened. It fails before the fix.
  • Replace the chain with a plain if (session != null) { restoreDraft(session.userId) } else { navigateToLogin() }.
  • Team rule: use x?.let { } ?: other only when the lambda can never return null. Otherwise use if/else.
  • Keep scope chains to one or two calls. Beyond that, use named locals.

Common mistakes

  • Using apply when you need the lambda's return value. apply always returns the object, so the last expression inside the block is ignored. If you wrote val result = obj.apply { computeSomething() }, result is obj, not the computed value. Use let or run instead when you need the lambda's result.
  • Nesting scope functions. Each nesting level adds another this or it that the reader must track, and an inner it hides an outer one. Extract intermediate results into named locals.
  • Using let on a non-null value just for style. x.let { it + 1 } is the same as x + 1 but adds a lambda and a layer of indentation. Reserve let for null-checks after ?., or for limiting the scope of a temporary value.
  • Confusing also and apply. Both return the object, but also passes it as it while apply passes it as this. Swapping also for apply breaks code that uses it (compile error). Swapping apply for also is worse when the outer class has a property with the same name: a bare name = "x" then changes the outer class, not the object.
  • Calling with on a nullable value. It compiles, but this is nullable inside, so every call needs ?.. Use value?.run { } so the block is skipped on null.
  • Ending ?.let \{ \} with a value that can be null before ?:. The fallback then runs even when the object was not null. Use if/else when the lambda can return null.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between apply and also?”

“When should you NOT use a scope function?”

“Explain the null-check idiom with let. What happens at the bytecode level?”

“A colleague wrote val config = builder.apply { setup(); true }. Is this correct?”

Quiz

What does apply return?

Which pair of scope functions both pass the object to the lambda as it?

What is the result of val x: Int? = null; val y = x?.let { it + 1 } ?: 42?

Which statement about with is correct?

0 of 4 answered

Mini task

Refactor a null-check chain into scope functions (15 min)

  1. Open a new Kotlin file. Write a function fun resolveHost(raw: String?, default: String): String that trims the input, checks it is not blank, and returns the trimmed value or the default. Use a plain if block first.

  2. Refactor the same function to use raw?.let { ... } ?: default. Remove the if block. Confirm the function still compiles and returns the same results for inputs " api.example.com ", "", and null. Note that the blank case works only because the lambda returns null for it: this is the same ?: rule as in the second production story.

  3. Add an also block inside the let lambda that prints "resolved: " + it to stdout. Confirm the function still returns the correct String (not Unit).

  4. Now write a second function fun buildUrl(host: String, path: String): String that uses apply on a StringBuilder to assemble "https://" + host + path, then calls .toString() on the result of apply.

  5. Add a third function fun logAndReturn(items: List<Int>): List<Int> that uses also to print the list size, then filters to even numbers. Confirm the return type is List<Int>, not Unit.

Done condition: All three functions compile, the also in step 3 does not change the return type, and the apply in step 4 is followed by .toString() so the function returns a String.

Next: Extension functions and properties