Infix functions for readable calls in Kotlin - Time & Space Complexity
Let's see how the time cost changes when using infix functions in Kotlin.
We want to know how the program's work grows as input gets bigger.
Analyze the time complexity of the following code snippet.
infix fun Int.times(str: String): String {
return str.repeat(this)
}
fun main() {
val result = 3 times "Hi"
println(result)
}
This code defines an infix function to repeat a string a number of times, then calls it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The string repeat function internally repeats the string by concatenation.
- How many times: It repeats the string exactly as many times as the integer value (here, 3 times).
As the number of repeats grows, the work to build the final string grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 string concatenations |
| 100 | About 100 string concatenations |
| 1000 | About 1000 string concatenations |
Pattern observation: The work grows roughly in direct proportion to the number of repeats.
Time Complexity: O(n)
This means the time to run grows linearly with how many times the string is repeated.
[X] Wrong: "Using an infix function makes the code faster or slower by itself."
[OK] Correct: The infix keyword only changes how we write the call, not how many steps the program takes.
Understanding how function calls affect time helps you explain your code clearly and shows you think about efficiency.
"What if the infix function repeated the string twice as many times internally? How would the time complexity change?"