Scope functions
Why it matters
- Scope functions appear in nearly every Kotlin codebase. Swapping
applyforletorrunsilently 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.
applyis like fixing the tool and handing it back to you. You get the tool, not the wrench you used.alsois like asking a colleague to inspect the tool while you keep working. You still hold the tool.letis like handing the tool to a specialist who gives you a new product. You get the result, not the original tool.withis like saying "work on this tool" without naming it on every line.runis 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.
| Function | Object in the lambda | Returns |
|---|---|---|
let | it | lambda's last expression |
run | this (no object for the plain run { } form) | lambda's last expression |
with | this (passed as an argument) | lambda's last expression |
apply | this | the object itself |
also | it | the 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,applyandalsoare extension functions on a genericT.withis 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. applyandalsoreturn the object, not the lambda's last expression. The last expression inside anapplyoralsoblock is ignored.x?.let { ... } ?: defaultis the idiomatic null-check. Inside the lambda,ithas the non-null type.- Watch out: in
x?.let { ... } ?: defaultthe default also runs when the lambda itself returnsnull, not only whenxis null. runhas two forms:obj.run { }(extension,thisis the object) andrun { }(top-level, no object, just a block that returns its last expression).withis not an extension, so you cannot writeobj?.with { }. If the object may be null,thisinsidewithis nullable. Preferobj?.run { }in that case.alsopasses the object as theitparameter. Insidealso,thisstill means the outer class, so you writeit.property. Insideapply, a barenamemeans the object'sname.- Chaining
applythenalsokeeps the type, because both return the object. Chainingapplythenletchanges the type to whatever theletlambda returns. - Scope functions are for short, single-purpose blocks. When a lambda grows long, replace it with a local
valand plain statements. - All five are
inlinefunctions 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. alsois 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
}parsePortusesletafter a safe call, so the null case is handled by?: -1without a separateifblock. Here the lambda never returns null, so the fallback runs only for a null input.buildQueryusesapplyon aStringBuilder.applyreturns theStringBuilderitself, so the function callstoString()on the result. AMaphas noforEachIndexed, so the code iterates overparams.entries. The standard library'sbuildString { }does the same job in one call.loadAndLogchainsalsothenfilter.alsoreturns the originalList<String>, sofilterreceives the right type. Swappingalsoforletwould break the chain:letreturns the lambda result, hereUnitfromprintln, sofilterwould not compile.summarizeuseswithto avoid writingstats.valuestwice. Inside the block,valuesmeansstats.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
- 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
applytorunto match the style of the rest of the file. runreturns the lambda's last expression. The last line was an assignment, so the lambda returnedUnitanddefaultConfig()now returnedUnitinstead ofConfig.- The only caller passed the result to a service locator that accepted
Any, so everything still compiled. The app crashed at startup with aClassCastExceptionwhen the config was read back asConfig.
- 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."
- A screen used
session?.let { restoreDraft(it.userId) } ?: run { navigateToLogin() }. restoreDraftreturnsDraft?:nullwhen the user has no saved draft.- The
?:runs its right side whenever the left side isnull. That happens whensessionis null, but also when theletlambda returnsnull. - Logged-in users with no saved draft were sent to the login screen. There was no crash and no error log, only confused users.
- 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 { } ?: otheronly when the lambda can never returnnull. Otherwise useif/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.
applyalways returns the object, so the last expression inside the block is ignored. If you wroteval result = obj.apply { computeSomething() },resultisobj, not the computed value. Useletorruninstead when you need the lambda's result. - Nesting scope functions. Each nesting level adds another
thisoritthat the reader must track, and an innerithides 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 asx + 1but adds a lambda and a layer of indentation. Reserveletfor null-checks after?., or for limiting the scope of a temporary value. - Confusing also and apply. Both return the object, but
alsopasses it asitwhileapplypasses it asthis. Swappingalsoforapplybreaks code that usesit(compile error). Swappingapplyforalsois worse when the outer class has a property with the same name: a barename = "x"then changes the outer class, not the object. - Calling with on a nullable value. It compiles, but
thisis nullable inside, so every call needs?.. Usevalue?.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. Useif/elsewhen the lambda can returnnull.
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)
-
Open a new Kotlin file. Write a function
fun resolveHost(raw: String?, default: String): Stringthat trims the input, checks it is not blank, and returns the trimmed value or the default. Use a plainifblock first. -
Refactor the same function to use
raw?.let { ... } ?: default. Remove theifblock. Confirm the function still compiles and returns the same results for inputs" api.example.com ","", andnull. Note that the blank case works only because the lambda returnsnullfor it: this is the same?:rule as in the second production story. -
Add an
alsoblock inside theletlambda that prints"resolved: " + itto stdout. Confirm the function still returns the correctString(notUnit). -
Now write a second function
fun buildUrl(host: String, path: String): Stringthat usesapplyon aStringBuilderto assemble"https://" + host + path, then calls.toString()on the result ofapply. -
Add a third function
fun logAndReturn(items: List<Int>): List<Int>that usesalsoto print the list size, then filters to even numbers. Confirm the return type isList<Int>, notUnit.
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.