Kotlin Scope Functions
The standard library has five small functions — let, run, with, apply and also — that execute a block of code in the context of an object. They don't add new abilities; they make code more concise and readable. The challenge is choosing the right one, so this chapter focuses on the two differences between them.
The two differences
- How the object is referred to inside the block: as
it(lambda argument) or asthis(receiver — members usable without a prefix). - What the call returns: the lambda result or the object itself.
| Function | Object is | Returns | Typical use |
|---|---|---|---|
let |
it |
lambda result | null checks (x?.let { }), transforming a value |
run |
this |
lambda result | compute a result from an object's members |
with(obj) |
this |
lambda result | call several functions on an object |
apply |
this |
the object | configure / initialise an object |
also |
it |
the object | side effects: logging, validation |
let
let is most often combined with the safe-call operator: the block runs only if the value isn't null.
fun main() {
val input: String? = " 42 "
val number = input?.let { it.trim().toInt() * 2 }
println(number)
val missing: String? = null
missing?.let { println("never printed") }
println(missing?.let { it.length } ?: "nothing")
}84
nothing
apply
apply runs the block with the object as this and returns the object — perfect for configuring something right after creating it:
class Email {
var to = ""
var subject = ""
var body = ""
override fun toString() = "To: $to | $subject | $body"
}
fun main() {
val mail = Email().apply {
to = "team@example.com"
subject = "Release"
body = "Version 2.0 is live!"
}
println(mail)
val list = mutableListOf(3, 1).apply { add(2); sort() }
println(list)
}To: team@example.com | Release | Version 2.0 is live!
[1, 2, 3]
also
also passes the object as it and returns the object — "and also do this". It fits side effects that shouldn't change the flow of a chain:
fun main() {
val result = listOf(5, 3, 8)
.also { println("Before: $it") }
.sorted()
.also { println("After sort: $it") }
.map { it * 10 }
println(result)
}Before: [5, 3, 8]
After sort: [3, 5, 8]
[30, 50, 80]
run and with
run and with both use this and return the block's result. run is called on an object (and works with ?.); with takes the object as an argument.
data class Cart(val items: List<Double>, val discount: Double)
fun main() {
val cart = Cart(listOf(10.0, 25.5, 4.5), 0.1)
val total = cart.run {
val sum = items.sum()
sum - sum * discount
}
println("Total: $total")
val report = with(StringBuilder()) {
append("Items: ").append(cart.items.size)
append(", max: ").append(cart.items.max())
toString()
}
println(report)
}Total: 36.0
Items: 3, max: 25.5
Picking the right one
A quick decision guide:
- Need to run code only when not null? →
?.let - Configuring a new object? →
apply - Adding a side effect (log, check) in a chain? →
also - Computing a value from an object's members? →
run(orwithif not null)
data class User(var name: String = "", var age: Int = 0)
fun main() {
val user = User()
.apply { name = "Noor"; age = 27 } // configure
.also { println("Created $it") } // log
val canVote = user.run { age >= 18 } // compute
val greeting = user.name.let { "Hello, $it" } // transform
println("$greeting - can vote: $canVote")
}Created User(name=Noor, age=27)
Hello, Noor - can vote: true
Tip: Don't nest scope functions deeply or chain too many —
itandthisquickly become ambiguous. If a block gets long, a normal variable and a few plain statements are clearer.
takeIf { … } and takeUnless { … } are close relatives: they return the object if the condition holds (or doesn't), otherwise null — e.g. input.takeIf { it.isNotBlank() } ?: "default".
Test yourself
Which scope function returns the object itself and uses this inside?
- let
- run
- apply
- also
What does "abc".let { it.length } return?
- "abc"
- 3
- Unit
- null
Which function is most idiomatic for executing code only when a nullable value is not null?
- ?.let { }
- with(x) { }
- apply { }
- also { } without ?.