0
0
Kotlinprogramming~5 mins

Also function behavior and use cases in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Also function behavior and use cases
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As n grows, the loop runs more times, doing the same steps each time.

Input Size (n)Approx. Operations
10About 10 adds and 10 prints
100About 100 adds and 100 prints
1000About 1000 adds and 1000 prints

Pattern observation: The work grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the number of items added.

Common Mistake

[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.

Interview Connect

Understanding how small helper functions like also affect time helps you explain your code clearly and think about performance in real projects.

Self-Check

What if we replaced also with apply in this loop? How would the time complexity change?