Inner class access to outer members in Kotlin - Time & Space Complexity
Let's see how the time it takes to run code changes when an inner class accesses members of its outer class.
We want to know how the number of steps grows as the input size changes.
Analyze the time complexity of the following code snippet.
class Outer(val numbers: List<Int>) {
inner class Inner {
fun sum(): Int {
var total = 0
for (num in numbers) {
total += num
}
return total
}
}
}
fun main() {
val outer = Outer(listOf(1, 2, 3, 4, 5))
val inner = outer.Inner()
println(inner.sum())
}
This code defines an outer class holding a list of numbers and an inner class that sums those numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of numbers inside the inner class's sum() function.
- How many times: Once for each number in the list (n times).
As the list gets bigger, the sum function takes longer because it adds each number one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The time grows directly with the number of items; doubling the list doubles the work.
Time Complexity: O(n)
This means the time to run the sum grows in a straight line with the size of the list.
[X] Wrong: "Accessing outer class members from the inner class adds extra loops or slows down the code significantly."
[OK] Correct: Accessing outer members is direct and does not add extra loops; the main time cost is still just looping through the list once.
Understanding how inner classes access outer members helps you explain code structure and performance clearly, a useful skill in many coding discussions.
What if the inner class stored a copy of the list instead of accessing the outer class's list directly? How would the time complexity change?