A nested class keeps a helper type close to the code that uses it. In Kotlin, a class declared inside another class does not implicitly reference the enclosing instance; this is the default behavior, unlike Java. section 4.1.4 section 4.0
A serializable view state
class Button : View { override fun getCurrentState(): State = ButtonState() override fun restoreState(state: State) { /* ... */ } class ButtonState : State { /* ... */ } } Here, ButtonState is a Kotlin nested class. It can represent Button-specific state without retaining a Button instance, avoiding the hidden outer reference that can make Java inner-class state fail serialization. Add the inner modifier only when the nested class must access its enclosing instance. section 4.1.4
Listing 4.15 Implementing View in Kotlin with a nested class
class Button : View {
override fun getCurrentState(): State = ButtonState()
override fun restoreState(state: State) { /*...*/ }
class ButtonState : State { /*...*/ } #1
}
Inspect the compact Kotlin implementation showing a nested ButtonState declaration inside Button. section 4.1.4
Use the Java comparison to choose the appropriate Kotlin form:
- Kotlin class A corresponds to Java static class A: neither stores an implicit reference to the enclosing object. section 4.1.4
- Kotlin inner class A corresponds to Java class A: it stores a reference to the enclosing object. section 4.1.4
- Prefer the default nested form for self-contained helpers; choose inner only when enclosing-instance access is required. section 4.1.4
