Any type as universal base in Kotlin - Time & Space Complexity
When using Kotlin's Any type as a universal base, it's important to see how operations on these objects grow with input size.
We want to know how the program's work changes as we handle more Any objects.
Analyze the time complexity of the following code snippet.
fun printAll(items: List) {
for (item in items) {
println(item.toString())
}
}
This code prints the string form of each item in a list of Any objects.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list.
- How many times: Once for every item in the list.
As the list gets bigger, the program prints more items, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print calls |
| 100 | 100 print calls |
| 1000 | 1000 print calls |
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 as the list gets bigger.
[X] Wrong: "Using Any makes the code slower because it has to check types for every item."
[OK] Correct: The loop runs once per item regardless of type. The toString() call is a simple method call and does not add extra loops or checks that change the overall time growth.
Understanding how operations on universal types like Any scale helps you explain performance clearly and confidently in interviews.
"What if we changed the list to a nested list of Any objects? How would the time complexity change?"