Explicit type declaration in Kotlin - Time & Space Complexity
Let's see how declaring types explicitly in Kotlin affects the time it takes for code to run.
We want to know if writing types by hand changes how fast the program works.
Analyze the time complexity of the following code snippet.
fun sumList(numbers: List): Int {
var sum: Int = 0 // explicit type declaration
for (num in numbers) {
sum += num
}
return sum
}
This function adds up all numbers in a list, using an explicit type for the sum variable.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every item in the list.
As the list gets bigger, the number of additions grows the same way.
| 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 finish grows in a straight line as the list gets bigger.
[X] Wrong: "Writing the type explicitly makes the code slower because it adds extra work."
[OK] Correct: The explicit type is just for the programmer and compiler; it does not change how many steps the program takes when running.
Understanding how code runs helps you explain your choices clearly and confidently in interviews.
"What if we replaced the list with a set? How would the time complexity change?"