Lambda with receiver concept in Kotlin - Time & Space Complexity
Let's see how the time needed to run a lambda with receiver changes as the input grows.
We want to know how the number of operations grows when using this Kotlin feature.
Analyze the time complexity of the following code snippet.
fun buildStringExample(n: Int): String = buildString {
repeat(n) {
append("*")
}
}
This code uses a lambda with receiver to build a string by adding n stars.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The repeat loop that calls append n times.
- How many times: Exactly n times, once per loop iteration.
Each time we add one more star, the loop runs one more time, so work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 appends |
| 100 | 100 appends |
| 1000 | 1000 appends |
Pattern observation: The work grows directly in proportion to n.
Time Complexity: O(n)
This means the time to build the string grows in a straight line as n increases.
[X] Wrong: "Using a lambda with receiver makes the code run instantly regardless of n."
[OK] Correct: The lambda with receiver just changes how we write code, but the loop inside still runs n times, so time grows with n.
Understanding how lambdas with receivers work helps you write clear Kotlin code and also think about how your code's speed changes with input size.
"What if we replaced repeat(n) with a nested loop inside the lambda? How would the time complexity change?"