Scope Functions Deep Dive
In this page:
Comparing Return Values
apply and also always return the original receiver object, while let, run, and with return whatever the lambda block itself produces as its last expression.
Example: Comparing Return Values
fun main() {
val listApply = mutableListOf(1, 2).apply { add(3) }
val sizeRun = mutableListOf(1, 2).run { add(3); size }
println("apply result: $listApply")
println("run result: $sizeRun")
}
Login to try C/C++/Java/PHP code in the editor
Comparing this vs it
apply, run, and with make the receiver available as this (often omitted), while let and also make it available as it, an explicit parameter name.
Example: Comparing this vs it
data class Box(var content: String)
fun main() {
val box = Box("empty")
box.apply { content = "full" } // this.content
box.also { println("Box now has: ${it.content}") } // it.content
}
Login to try C/C++/Java/PHP code in the editor
Choosing let for Transformation
let is ideal when you want to transform a value into something else and get that new result back, especially in combination with a safe call on a nullable value.
Example: Choosing let for Transformation
fun main() {
val name: String? = "kotlin"
val length = name?.let { it.length }
println("Length: $length")
}
Login to try C/C++/Java/PHP code in the editor
Choosing apply for Configuration
apply is ideal when configuring an object's properties and you want the fully configured object itself back at the end, without needing a separate computed result.
Example: Choosing apply for Configuration
class Settings {
var darkMode = false
var fontSize = 12
}
fun main() {
val settings = Settings().apply {
darkMode = true
fontSize = 16
}
println("Dark mode: ${settings.darkMode}, Font size: ${settings.fontSize}")
}
Login to try C/C++/Java/PHP code in the editor
- Choosing the wrong scope function for the job, such as using
applywhen the intended result was the block's own computed value (which needsrunorletinstead). - Nesting scope functions deeply, making it hard to tell which
this/itbelongs to which block. - Using a scope function purely for style when a plain statement would be clearer and just as short.
let,run,with,apply, andalsoall execute a block against a receiver but differ in what they return and whether the receiver isthisorit.applyandalsoreturn the original receiver;let,run, andwithreturn the block's result.apply,run, andwithexpose the receiver asthis;letandalsoexpose it asit.- Choosing the right scope function comes down to what you need back: the original object, or a transformed result.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: