Apply function behavior and use cases in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run code using Kotlin's apply function changes as the input grows.
Specifically, how does using apply affect the number of steps the program takes?
Analyze the time complexity of the following code snippet.
val list = mutableListOf()
val n = 1000
val result = list.apply {
for (i in 1..n) {
add(i)
}
}
println(result.size)
This code uses apply to add numbers from 1 to n into a list, then prints the list size.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop that adds elements to the list. - How many times: Exactly
ntimes, once for each number from 1 to n.
Each time we increase n, the loop runs that many more times, adding one element per run.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with the size of n. Double n, double the work.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the number of items added.
[X] Wrong: "Using apply makes the code run faster because it's a special function."
[OK] Correct: apply just helps organize code; it doesn't change how many times the loop runs or how much work is done.
Understanding how helper functions like apply affect time helps you explain your code clearly and shows you know what really costs time in programs.
"What if we replaced the for loop inside apply with a call to repeat(n)? How would the time complexity change?"
Practice
apply function do in Kotlin?Solution
Step 1: Understand the purpose of
Theapplyapplyfunction executes a block of code on the object it is called on.Step 2: Identify the return value of
It always returns the original object after applying the block, not a new value.applyFinal Answer:
Runs code on an object and returns the same object -> Option AQuick Check:
applyreturns the object itself [OK]
- Thinking apply returns the last expression result
- Confusing apply with let or run
- Assuming apply creates a new object
apply on an object person to set its name property to "Alice"?Solution
Step 1: Identify the correct lambda syntax for
applyapplytakes a lambda with receiver wherethisis the object, so properties can be set directly.Step 2: Check each option's syntax
person.apply { name = "Alice" } correctly usesperson.apply { name = "Alice" }. apply(person) { name = "Alice" } is invalid syntax. person.apply(name = "Alice") wrongly passes a parameter. person.apply { setName("Alice") } assumes a setter method which may not exist.Final Answer:
person.apply { name = "Alice" } -> Option AQuick Check:
Useobject.apply { property = value }syntax [OK]
- Passing parameters directly to apply
- Using parentheses instead of curly braces
- Calling non-existent setter methods
val list = mutableListOf<Int>().apply {
add(1)
add(2)
add(3)
}
println(list)Solution
Step 1: Understand what
Theapplydoes on the listapplyblock adds 1, 2, and 3 to the mutable list.Step 2: Check the returned value of
applyapplyreturns the original list after adding the elements, solistcontains [1, 2, 3].Final Answer:
[1, 2, 3] -> Option DQuick Check:
apply adds elements and returns the list [OK]
- Expecting apply to return last added element
- Thinking list is empty after apply
- Confusing apply with run or let
apply:
val map = mutableMapOf()
map.apply {
put("a", 1)
put("b", 2)
}
println(map.get("c"))Solution
Step 1: Check the apply block usage
Theapplyblock correctly adds two entries to the map.Step 2: Understand the map.get("c") call
Since key "c" does not exist,getreturns null, which is printed without error.Final Answer:
No error; output is null -> Option CQuick Check:
Accessing missing key returns null, no error [OK]
- Expecting runtime error for missing key
- Thinking apply must return a value explicitly
- Confusing map access syntax
StringBuilder in Kotlin to build the string "Hello World!" using apply. Which code snippet correctly does this?Solution
Step 1: Understand
Theapplyreturns the object itselfapplyblock configures theStringBuilder, but to get the string,toString()must be called after.Step 2: Check each option's correctness
val result = StringBuilder().apply { append("Hello"); append(" World!") }.toString() callstoString()afterapply, returning the built string. val result = StringBuilder().apply { append("Hello World!") } returns theStringBuilderobject, not the string. val result = StringBuilder().apply { append("Hello"); append(" World!") } missestoString(). val result = StringBuilder().apply { append("Hello"); append(" World!") }.toString misses parentheses ontoString, causing error.Final Answer:
val result = StringBuilder().apply { append("Hello"); append(" World!") }.toString() -> Option BQuick Check:
CalltoString()after apply to get string [OK]
- Forgetting to call toString() after apply
- Missing parentheses on toString
- Expecting apply to return string automatically
Ready to prove it?
Pass the test and this pattern moves unknown
