Extension function syntax in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run an extension function changes as the input grows.
How does adding an extension function affect the work done when called on different input sizes?
Analyze the time complexity of the following Kotlin extension function.
fun List<Int>.sumElements(): Int {
var sum = 0
for (element in this) {
sum += element
}
return sum
}
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
println(numbers.sumElements())
}
This code adds a new function to List<Int> that sums all its elements.
Look at what repeats when the function runs.
- Primary operation: Looping through each element in the list.
- How many times: Once for every item in the list.
As the list gets bigger, the function does more work by adding more numbers.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the list size.
[X] Wrong: "Extension functions run instantly no matter the input size."
[OK] Correct: Even though the function is added outside the class, it still runs the code inside, which depends on the input size.
Knowing how extension functions behave helps you explain your code clearly and understand performance when adding new features.
"What if the extension function called another function inside that also loops over the list? How would the time complexity change?"