Chaining scope functions in Kotlin - Time & Space Complexity
When we chain scope functions in Kotlin, we run several operations one after another on the same object.
We want to know how the total work grows as the input or number of chained calls increases.
Analyze the time complexity of the following code snippet.
val result = listOf(1, 2, 3, 4, 5)
.filter { it % 2 == 0 }
.map { it * 2 }
.take(2)
.sum()
This code filters even numbers, doubles them, takes the first two, then sums them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Each scope function like filter and map loops over the list elements.
- How many times: Each function processes the list once, so multiple passes happen in sequence.
Each chained function goes through the list, so the total work adds up.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 operations (3 passes x 10 items) |
| 100 | About 300 operations (3 passes x 100 items) |
| 1000 | About 3000 operations (3 passes x 1000 items) |
Pattern observation: The total work grows roughly linearly with input size but multiplies by the number of chained functions.
Time Complexity: O(k * n)
This means the time grows linearly with the list size n and the number of chained scope functions k.
[X] Wrong: "Chaining scope functions runs in constant time because it looks like one statement."
[OK] Correct: Each function processes the whole list separately, so the total work adds up, not stays the same.
Understanding how chaining affects time helps you write efficient Kotlin code and explain your reasoning clearly in interviews.
"What if we replaced multiple chained scope functions with a single loop doing all steps? How would the time complexity change?"
Practice
Solution
Step 1: Understand the purpose of scope functions
Scope functions let you run code blocks on an object, often returning the object or a result.Step 2: Recognize chaining benefit
Chaining lets you call many scope functions one after another on the same object without repeating its name.Final Answer:
Perform multiple operations on one object without repeating its name -> Option AQuick Check:
Chaining scope functions = clean, repeated operations [OK]
- Thinking chaining creates new objects
- Confusing chaining with loops
- Believing chaining changes data types automatically
apply and also on an object obj?Solution
Step 1: Recall correct chaining syntax
In Kotlin, scope functions are called with dot notation and lambda blocks inside curly braces.Step 2: Check each option
obj.apply { }.also { } uses correct dot chaining with braces. obj.apply() also() misses dots and braces. apply(obj) { } also { } uses wrong function call style. obj.apply { } also { } misses dot beforealso.Final Answer:
obj.apply { }.also { } -> Option AQuick Check:
Dot + braces = correct chaining syntax [OK]
- Omitting dots between functions
- Using parentheses instead of braces for lambdas
- Calling scope functions like regular functions without object
val result = "hello".also { println(it.uppercase()) }.length
println(result)Solution
Step 1: Understand
alsobehavioralsoruns the lambda with the object asit, prints uppercase "HELLO", then returns the original string "hello".Step 2: Calculate
Afterresultalso,lengthis called on "hello", which is 5. Thenprintln(result)prints 5.Final Answer:
HELLO 5 -> Option DQuick Check:
also prints uppercase, length returns 5 [OK]
- Thinking also returns uppercase string
- Confusing print order
- Expecting length to be printed before uppercase
val text = "kotlin"
text.let { it.uppercase() }.apply { println(this) }Solution
Step 1: Analyze
letreturn valueletreturns the lambda result, hereit.uppercase(), a new String "KOTLIN".Step 2: Check
applyreceiverapplyis called on the uppercase string, sothisinsideapplyis "KOTLIN" andprintln(this)prints "KOTLIN".Step 3: Identify the problem
The originaltextis "kotlin", butapplyprints the uppercase string, not the original. This may be unexpected if you want to print original.Final Answer:
let does not return the original object, so apply prints wrong value -> Option CQuick Check:
let returns lambda result, not original object [OK]
- Assuming let returns original object
- Thinking apply needs braces
- Believing no error exists
val nums = mutableListOf(1, 2, 3), which chained scope function call correctly adds 4, prints the list, and returns the updated list?Solution
Step 1: Understand return values of scope functions
applyreturns the original object after running the block,alsoreturns the original object too,letreturns lambda result,runreturns lambda result.Step 2: Check each option
nums.apply { add(4) }.also { println(it) } adds 4 insideapply, then prints list inalso, returning the updated list. nums.let { it.add(4) }.also { println(it) }'sletreturnsUnitfromadd, soalsoprintsUnit. nums.also { add(4) }.apply { println(this) } has syntax error ('add' unresolved inalsoblock, needsit.add(4)). nums.run { add(4); println(this) } returnsUnitfromrun.Final Answer:
nums.apply { add(4) }.also { println(it) } -> Option BQuick Check:
apply returns object, also prints it [OK]
- Using let which returns Unit from add
- Expecting run to return the list
- Confusing order of operations in chaining
Ready to prove it?
Pass the test and this pattern moves unknown
