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?"
Practice
Solution
Step 1: Understand nested class behavior
Nested classes are static by default and cannot access outer class members directly.Step 2: Understand inner class behavior
Inner classes use theinnerkeyword and can access outer class members.Final Answer:
An inner class can access members of the outer class, but a nested class cannot. -> Option AQuick Check:
Inner class = access outer members [OK]
- Thinking nested classes can access outer members
- Confusing inner classes as static
- Assuming both classes behave the same
Solution
Step 1: Recall inner class syntax
In Kotlin, inner classes require theinnerkeyword to access outer class members.Step 2: Check options for correct keyword
class Outer { inner class Inner { } } usesinner class Inner, which is the correct syntax.Final Answer:
class Outer { inner class Inner { } } -> Option CQuick Check:
Use 'inner' keyword for inner classes [OK]
- Omitting 'inner' keyword for inner classes
- Using 'static' keyword which is invalid in Kotlin
- Confusing 'open' with 'inner'
class Outer(val name: String) {
inner class Inner {
fun greet() = "Hello, $name"
}
}
fun main() {
val outer = Outer("Kotlin")
val inner = outer.Inner()
println(inner.greet())
}Solution
Step 1: Understand inner class access
The inner class can access the outer class propertynamebecause it is declared withinner.Step 2: Trace the code execution
Creatingouterwith name "Kotlin" and theninnerinstance callsgreet()which returns "Hello, Kotlin".Final Answer:
Hello, Kotlin -> Option BQuick Check:
Inner class accesses outer property correctly [OK]
- Assuming inner class cannot access outer properties
- Expecting null or empty output
- Thinking code causes compilation error
class Outer {
class Nested {
fun printMessage() = println("Hello from Nested")
}
}
fun main() {
val nested = Outer.Nested()
nested.printMessage()
println(nested.printMessage())
}Solution
Step 1: Check nested class instantiation
Nested classes are static by default and can be instantiated without an Outer instance, so no error here.Step 2: Analyze println usage
The functionprintMessage()prints a message and returnsUnit. Callingprintln(nested.printMessage())prints the message and then printskotlin.Unit, which is allowed.Step 3: Confirm no errors
There is no compilation or runtime error; the code runs and produces output as written.Final Answer:
No errors; code runs and prints correctly. -> Option DQuick Check:
Nested class instantiation and Unit printing both OK [OK]
- Thinking nested class needs Outer instance
- Expecting compilation error on nested class
- Ignoring Unit return type printing
class Outer(val x: Int) {
inner class Inner {
fun multiply(y: Int) = x * y
}
class Nested {
fun multiply(y: Int) = y * 2
}
}
fun main() {
val outer = Outer(5)
val inner = outer.Inner()
val nested = Outer.Nested()
println(inner.multiply(3))
println(nested.multiply(3))
}Solution
Step 1: Calculate inner class multiply
Inner class accesses outer propertyx=5, somultiply(3)returns 5*3=15.Step 2: Calculate nested class multiply
Nested class method multiplies input by 2, somultiply(3)returns 6.Step 3: Confirm output lines
Printing inner.multiply(3) prints 15, printing nested.multiply(3) prints 6 on next line.Final Answer:
15 6 -> Option AQuick Check:
Inner uses outer x, nested doubles input [OK]
- Assuming nested class can access outer x
- Mixing up multiply results
- Expecting compilation error
Ready to prove it?
Pass the test and this pattern moves unknown
