Run function behavior and use cases in Kotlin - Time & Space Complexity
Let's see how the time cost grows when using Kotlin's run function.
We want to know how the number of steps changes as the input or code inside run grows.
Analyze the time complexity of the following code snippet.
val result = run {
var sum = 0
for (i in 1..n) {
sum += i
}
sum
}
println(result)
This code uses run to calculate the sum of numbers from 1 to n.
Look for loops or repeated steps inside the run block.
- Primary operation: The
forloop adding numbers. - How many times: It runs n times, once for each number from 1 to n.
As n grows, the loop runs more times, so the work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with n; doubling n doubles the steps.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of n.
[X] Wrong: "The run function itself adds extra loops or slows down the code a lot."
[OK] Correct: The run function just runs the code inside once; it doesn't add loops or repeat work.
Understanding how small helpers like run affect time helps you explain your code clearly and think about efficiency in real projects.
"What if we replaced the for loop inside run with a nested loop running n times inside another loop running n times? How would the time complexity change?"
Practice
run function do when called without an object?Solution
Step 1: Understand run without receiver
Whenrunis called without an object, it simply executes the block of code inside it.Step 2: Identify the return value
The function returns the value of the last expression inside the block.Final Answer:
Executes the given block and returns the last expression's value -> Option CQuick Check:
run without object returns last expression [OK]
- Thinking run creates a new thread
- Assuming run delays execution
- Believing run throws error without explicit return
run with an object in Kotlin?Solution
Step 1: Identify correct run usage with receiver
Therunfunction is called as an extension on the object:obj.run { ... }.Step 2: Check syntax correctness
val result = obj.run { this.property + 1 } correctly usesobj.run { this.property + 1 }without extra parentheses or misplaced dots.Final Answer:
val result = obj.run { this.property + 1 } -> Option BQuick Check:
run called as extension function on object [OK]
- Using dot after run like run.obj
- Adding empty parentheses after run
- Calling run without object but expecting receiver
val result = run {
val x = 5
val y = 10
x + y
}
println(result)Solution
Step 1: Execute the run block
The block declaresx = 5andy = 10, then returnsx + ywhich is 15.Step 2: Print the result
The variableresultholds 15, soprintln(result)outputs 15.Final Answer:
15 -> Option DQuick Check:
run returns last expression value 15 [OK]
- Concatenating numbers as strings
- Expecting null because no explicit return
- Thinking run causes compilation error
run:
val text = "Hello"
val length = text.run {
val len = length
}
println(length)Solution
Step 1: Analyze run block return
The run block declaresval len = lengthbut does not return any expression explicitly, so it returnsUnit.Step 2: Check assignment to length variable
Variablelengthis assigned the result of run, which isUnit, not the integer length of the string.Final Answer:
The run block does not return a value, so length is assigned Unit -> Option AQuick Check:
run returns last expression; no explicit return means Unit [OK]
- Assuming len is returned automatically
- Confusing property length with variable
- Thinking run cannot be called on String
val numbers = listOf(1, null, 3, null, 5), how can you use run to compute the sum of non-null values safely in Kotlin?Solution
Step 1: Use run as extension on list
Callingnumbers.run { ... }lets you access list functions directly inside the block.Step 2: Filter non-null and sum
Inside the block,filterNotNull()removes nulls, thensum()adds remaining numbers.Final Answer:
val sum = numbers.run { filterNotNull().sum() } -> Option AQuick Check:
run with receiver simplifies code, returns last expression [OK]
- Passing list as argument to run incorrectly
- Calling sum() without filtering nulls
- Using run without receiver and accessing list members directly
Ready to prove it?
Pass the test and this pattern moves unknown
