Inner classes and nested classes in Kotlin - Time & Space Complexity
Let's see how the time it takes to run code with inner and nested classes changes as the input grows.
We want to know which parts of the code repeat and how that affects the total work done.
Analyze the time complexity of the following code snippet.
class Outer {
private val numbers = listOf(1, 2, 3, 4, 5)
inner class Inner {
fun sum(): Int {
var total = 0
for (num in numbers) {
total += num
}
return total
}
}
class Nested {
fun greet() = "Hello"
}
}
This code defines an outer class with an inner class that sums a list and a nested class that just says hello.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop inside theInner.sum()method that goes through the listnumbers. - How many times: It runs once for each item in the list, so as many times as the list size.
As the list size grows, the loop inside Inner.sum() runs more times, adding up numbers one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the list size. Double the list, double the work.
Time Complexity: O(n)
This means the time to run the sum grows in a straight line with the number of items in the list.
[X] Wrong: "The nested class Nested affects the time it takes to sum the numbers."
[OK] Correct: The nested class Nested does not access the list or run loops, so it does not add to the time complexity of summing.
Understanding how inner and nested classes work helps you explain how your code runs and grows, a skill that shows you think clearly about your programs.
"What if the Inner class stored the sum result and reused it instead of looping every time? How would the time complexity change?"