Inner vs Nested Class in Kotlin: Key Differences and Usage
nested class is a static class that cannot access members of its outer class, while an inner class is non-static and can access the outer class's members. You declare an inner class with the inner keyword, enabling it to hold a reference to the outer class instance.Quick Comparison
Here is a quick side-by-side comparison of inner and nested classes in Kotlin.
| Aspect | Nested Class | Inner Class |
|---|---|---|
| Definition | Static class inside another class | Non-static class inside another class |
| Access to outer class members | No access | Can access outer class members |
| Keyword used | No keyword needed | inner keyword required |
| Reference to outer class | No reference | Holds reference to outer class instance |
| Instance creation | Can be created without outer class instance | Requires outer class instance to create |
| Use case | Grouping without outer context | Accessing outer class data |
Key Differences
A nested class in Kotlin is like a static class in Java. It does not hold a reference to the outer class, so it cannot access the outer class's properties or functions directly. This makes it lightweight and useful when you want to group classes logically without needing the outer class context.
On the other hand, an inner class is marked with the inner keyword. It keeps a reference to an instance of the outer class, allowing it to access the outer class's members directly. This is helpful when the inner class needs to work closely with the outer class's data or behavior.
Because an inner class holds a reference to the outer class, you must create an instance of the outer class first before creating the inner class instance. Nested classes do not have this requirement and can be instantiated independently.
Code Comparison
class Outer { private val outerValue = "Outer" class Nested { fun nestedFunction() = "Nested class cannot access outerValue" } inner class Inner { fun innerFunction() = "Inner class can access: $outerValue" } } fun main() { val nested = Outer.Nested() println(nested.nestedFunction()) val outer = Outer() val inner = outer.Inner() println(inner.innerFunction()) }
Inner Class Equivalent
class Outer { private val outerValue = "Outer" inner class Inner { fun innerFunction() = "Inner class can access: $outerValue" } } fun main() { val outer = Outer() val inner = outer.Inner() println(inner.innerFunction()) }
When to Use Which
Choose a nested class when you want to group a class inside another without needing access to the outer class's properties or functions. It is simpler and does not hold a reference to the outer class, saving memory.
Choose an inner class when the inner class needs to access or modify the outer class's members. This is useful for tightly coupled logic where the inner class depends on the outer class instance.