Scope functions help you write less repeated code by letting you work with an object inside a small block. This makes your code shorter and easier to read.
Why scope functions reduce boilerplate in Kotlin
object.let { it -> // use it here } object.run { // use this here } object.apply { // configure this here } object.also { it -> // do something with it } object.takeIf { condition } object.takeUnless { condition }
Each scope function has a slightly different way to access the object: let and also use it, while run and apply use this.
Some return the object itself, others return the result of the block.
let to convert a string to uppercase without repeating the string variable.val result = "hello".let { it.uppercase() } println(result)
apply lets you set properties on an object inside a block, then returns the object.val person = Person().apply { name = "Alice" age = 30 } println(person.name)
run uses this to access the object and returns the last expression.val length = "Kotlin".run { println(this) length } println(length)
also lets you do something with the object (like logging) and returns the object.val numbers = mutableListOf(1, 2, 3).also { println("Original list: $it") } println(numbers)
This program creates a User object and sets its properties using apply. Then it uses let to build a greeting message without repeating the user variable.
data class User(var name: String, var age: Int) fun main() { val user = User("", 0).apply { name = "Bob" age = 25 } val greeting = user.let { "Hello, ${it.name}, age ${it.age}!" } println(greeting) }
Scope functions help keep your code clean and avoid repeating the same object name many times.
Choose the right scope function based on whether you want to return the object or a different result.
Using scope functions can make your code easier to read and maintain.
Scope functions reduce repeated code by letting you work inside a small block with an object.
They improve readability by limiting how often you write the object name.
Different scope functions have different ways to access the object and return values.
Practice
Solution
Step 1: Understand boilerplate in Kotlin
Boilerplate means writing the same object name multiple times when calling its properties or functions.Step 2: Role of scope functions
Scope functions let you work inside a block where the object is implicit, so you don't repeat its name.Final Answer:
They let you access an object inside a block without repeating its name -> Option AQuick Check:
Scope functions reduce repeated object names [OK]
- Thinking scope functions generate variable names
- Confusing scope functions with loops
- Believing scope functions convert functions to classes
let scope function in Kotlin?Solution
Step 1: Recall
Theletsyntaxletfunction is called on an object with a lambda receiving the object asitor a named parameter.Step 2: Check each option
object.let { it -> println(it) } correctly callsobject.let { it -> ... }. Others have wrong syntax or order.Final Answer:
object.let { it -> println(it) } -> Option DQuick Check:
letcalled on object with lambda [OK]
object.let { it -> ... } is correct [OK]- Placing
letbefore the object - Omitting parentheses or braces
- Using wrong lambda parameter names
val name = "Alice"
val result = name.run {
println(this)
length
}
println(result)Solution
Step 1: Understand
runbehaviorrunexecutes the block withthisas the object and returns the last expression's value.Step 2: Trace the code
Insiderun,println(this)prints "Alice". The block returnslengthwhich is 5. Thenprintln(result)prints 5.Final Answer:
Alice 5 -> Option AQuick Check:
runprints object then returns last expression [OK]
run returns last expression, prints inside block [OK]- Confusing
thiswithit - Expecting
runto return the object - Ignoring the printed output inside the block
apply:
val builder = StringBuilder()
builder.apply {
append("Hello")
}
println(builder.toString())Solution
Step 1: Understand
applyusageapplyruns the block withthisas the object and returns the object itself.Step 2: Check code correctness
The code appends "Hello" insideapplyand then prints the builder content. This is valid and prints "Hello".Final Answer:
No error; code works and prints "Hello" -> Option CQuick Check:
applyreturns object, no return needed [OK]
apply returns object; no explicit return needed [OK]- Thinking return is required inside apply
- Believing apply can't be used with StringBuilder
- Trying to call append outside apply unnecessarily
Solution
Step 1: Identify scope function behavior
applyruns a block withthisas the object and returns the object itself, perfect for initialization.Step 2: Compare with other functions
runreturns last expression,letreturns lambda result,alsoreturns object but usesit.applyis best for adding elements and returning the list.Final Answer:
apply -> Option BQuick Check:
Initialize and return object = apply [OK]
apply returns object after block; ideal for initialization [OK]- Choosing
letwhich returns lambda result - Confusing
alsowithapply - Using
runwhich returns last expression, not object
Ready to prove it?
Pass the test and this pattern moves unknown
