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?
Practice
also function do in Kotlin?Solution
Step 1: Understand the purpose of
Thealsoalsofunction is used to run some extra code on an object without changing it.Step 2: Check the return value of
It returns the original object, not a transformed copy.alsoFinal Answer:
Runs extra code on an object and returns the original object -> Option AQuick Check:
alsoreturns original object [OK]
- Thinking it returns a transformed object
- Confusing it with map or let
- Assuming it stops program execution
also with a variable num in Kotlin?Solution
Step 1: Recall the syntax of
Thealsoalsofunction is called on an object with a lambda block:object.also { ... }.Step 2: Check each option for correct syntax
num.also { println(it) } uses the correct dot call and lambda syntax. Options A, C, and D have syntax errors or wrong usage.Final Answer:
num.also { println(it) } -> Option DQuick Check:
Correctalsosyntax uses dot and lambda [OK]
- Calling also as a standalone function
- Missing curly braces for lambda
- Using arrow without lambda properly
val list = mutableListOf(1, 2, 3)
val result = list.also { it.add(4) }
println(result)Solution
Step 1: Understand what
Thealsodoes herealsoblock adds 4 to the mutable list. Since the list is mutable, it changes the original list.Step 2: Check the returned value
alsoreturns the original list, now modified with 4 added.Final Answer:
[1, 2, 3, 4] -> Option CQuick Check:
also returns original object after modification [OK]
- Thinking also returns a new list
- Ignoring that list is mutable
- Expecting original list without 4
also:val text = "Hello"
text.also { it = it + " World" }
println(text)Solution
Step 1: Analyze the lambda parameter 'it'
Inalso, 'it' is a val (read-only), so you cannot reassign it inside the lambda.Step 2: Check the code for reassignment
The code tries to doit = it + " World", which is illegal and causes a compilation error.Final Answer:
Cannot reassign 'it' inside also lambda -> Option BQuick Check:
Lambda parameter 'it' is read-only [OK]
- Trying to reassign 'it' inside lambda
- Confusing also with let for transformations
- Ignoring immutability of lambda parameters
also to log each name while returning the original list unchanged?val users = listOf("Alice", "Bob", "Carol")
// Insert code here
println(users)Solution
Step 1: Understand the goal
We want to log each name but keep the original list unchanged and returned.Step 2: Check each option's behavior
users.also { it.forEach { name -> println(name) } } usesalsoto run logging side effects and returns the original list. Options B and C return transformed or Unit types, and D returns Unit.Final Answer:
users.also { it.forEach { name -> println(name) } } -> Option AQuick Check:
also runs side effects and returns original object [OK]
- Using map which changes the list
- Using let which returns last lambda result
- Using forEach alone which returns Unit
Ready to prove it?
Pass the test and this pattern moves unknown
