Testing scope functions and lambdas in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run Kotlin collection functions and lambdas changes as the input grows.
How does the number of operations increase when using these functions with larger data?
Analyze the time complexity of the following code snippet.
val numbers = listOf(1, 2, 3, 4, 5)
numbers.map { it * 2 }
.filter { it > 5 }
.forEach { println(it) }
This code doubles each number, keeps those greater than 5, and prints them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
map,filter, andforEacheach loop over the list. - How many times: Each function goes through all items once, so three times total over the list.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 (3 times 10) |
| 100 | About 300 (3 times 100) |
| 1000 | About 3000 (3 times 1000) |
Pattern observation: The total work grows directly with the size of the list, multiplied by the number of functions called.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input list gets bigger.
[X] Wrong: "Using multiple collection functions like map and filter makes the code run in constant time because they are built-in."
[OK] Correct: Each collection function processes the whole list once, so the total time grows with the input size, not fixed.
Understanding how collection functions and lambdas affect performance helps you write clear and efficient Kotlin code, a skill valued in many coding challenges and real projects.
"What if we combined map and filter into a single loop using sequence? How would the time complexity change?"
Practice
Solution
Step 1: Understand scope function behavior
Thealsofunction executes the lambda with the object asitand returns the original object.Step 2: Compare with other functions
letreturns the lambda result,runreturns lambda result,applyreturns the object but usesthisinside lambda.Final Answer:
also -> Option BQuick Check:
Returns original object after lambda = also [OK]
- Confusing 'also' with 'let' return values
- Mixing 'apply' and 'also' usage
- Assuming 'run' returns the object
let scope function on a nullable variable name?Solution
Step 1: Check nullable safe call usage
To safely callleton a nullable variable, use the safe call operator?..Step 2: Validate lambda syntax
The lambda must be enclosed in braces{}and useitas the implicit parameter.Final Answer:
name?.let { println(it) } -> Option AQuick Check:
Safe call with lambda braces = name?.let { println(it) } [OK]
- Omitting safe call operator on nullable
- Incorrect lambda syntax without braces
- Trying to call let as a standalone function
val result = "hello".run {
println(this.uppercase())
this.length
}
println(result)Solution
Step 1: Understand
Therunbehaviorrunfunction executes the lambda withthisas the receiver and returns the lambda's last expression.Step 2: Trace the code execution
Inside lambda,println(this.uppercase())prints "HELLO". Thenthis.lengthreturns 5, assigned toresult. Finally,println(result)prints 5.Final Answer:
HELLO 5 -> Option DQuick Check:
run prints uppercase then returns length = HELLO and 5 [OK]
- Assuming run returns the printed string
- Confusing this with it inside lambda
- Mixing order of printed lines
val numbers = listOf(1, 2, 3)
numbers.also {
it.add(4)
}
println(numbers)Solution
Step 1: Check list mutability
listOfcreates an immutable list; callingaddis not allowed.Step 2: Understand scope function effect
alsoruns the lambda but does not change immutability; trying to add causes a runtime error.Final Answer:
Cannot call add on immutable list -> Option CQuick Check:
Immutable list blocks add() method = Cannot call add on immutable list [OK]
- Assuming also changes list mutability
- Ignoring immutable list restrictions
- Thinking lambda syntax is wrong
val nums = listOf(1, null, 3, null, 5), which code snippet correctly uses scope functions and lambdas to create a list of doubled non-null values?Solution
Step 1: Remove nulls before mapping
UsefilterNotNull()to exclude null values safely.Step 2: Map remaining values to double
Applymap { it * 2 }on non-null list to double each integer.Final Answer:
nums.filterNotNull().map { it * 2 } -> Option AQuick Check:
Filter nulls then map doubling = nums.filterNotNull().map { it * 2 } [OK]
- Mapping before filtering nulls causes null results
- Using unsafe !! operator risking exceptions
- Misusing also or run without returning correct list
Ready to prove it?
Pass the test and this pattern moves unknown
