Type constraints with upper bounds in Kotlin - Time & Space Complexity
We want to understand how the time needed to run code changes when we use type constraints with upper bounds in Kotlin.
Specifically, how does limiting types affect the number of steps the program takes?
Analyze the time complexity of the following code snippet.
fun <T : Number> sumNumbers(numbers: List<T>): Double {
var sum = 0.0
for (num in numbers) {
sum += num.toDouble()
}
return sum
}
This function sums a list of numbers where the type is limited to subclasses of Number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the list.
- How many times: Once for every item in the input list.
As the list gets bigger, the function does more additions and conversions, one for each item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions and conversions |
| 100 | About 100 additions and conversions |
| 1000 | About 1000 additions and conversions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items in the list.
[X] Wrong: "Adding a type constraint makes the function slower because it adds extra checks."
[OK] Correct: The type constraint only limits what types can be used; it does not add extra loops or repeated work during execution.
Understanding how type constraints affect performance helps you explain your code choices clearly and shows you know how code runs as data grows.
"What if we changed the input from a List to a Set? How would the time complexity change?"