Also function behavior and use cases in Kotlin - Time & Space Complexity
We want to understand how the time cost changes when using Kotlin's also function.
How does adding also affect the speed of our code?
Analyze the time complexity of this Kotlin code using also.
val list = mutableListOf()
for (i in 1..n) {
list.add(i).also {
println("Added $i")
}
}
This code adds numbers from 1 to n into a list and prints each added number using also.
Look at what repeats in the code.
- Primary operation: Loop runs from 1 to n, adding and printing each number.
- How many times: Exactly n times, once per number.
As n grows, the loop runs more times, doing the same steps each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 adds and 10 prints |
| 100 | About 100 adds and 100 prints |
| 1000 | About 1000 adds and 1000 prints |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time grows in a straight line with the number of items added.
[X] Wrong: "Using also makes the code slower by a lot because it adds extra work."
[OK] Correct: also just runs a small extra step per item, so it adds a small constant time per loop, not changing the overall growth pattern.
Understanding how small helper functions like also affect time helps you explain your code clearly and think about performance in real projects.
What if we replaced also with apply in this loop? How would the time complexity change?