Single-expression functions in Kotlin - Time & Space Complexity
We want to see how fast a single-expression function runs as the input size changes.
How does the work inside this short function grow when input grows?
Analyze the time complexity of the following code snippet.
fun sumList(numbers: List<Int>) = numbers.sum()
This function returns the sum of all numbers in a list using a single-expression style.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The function calls
sum()which goes through each number in the list once. - How many times: It visits every item in the list exactly one time.
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; double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of the list.
[X] Wrong: "Because the function is one line, it must run instantly no matter the input size."
[OK] Correct: Even a single line can do a lot of work if it processes every item in a list. The length of the list matters more than the number of lines.
Understanding how simple-looking functions still depend on input size helps you explain your code clearly and think about efficiency in real projects.
"What if we changed the function to return the first item instead of summing all? How would the time complexity change?"