liveBook · Manning

Nested class

As explained in Kotlin in Action, 2E

A nested class is a class declared inside another class; in Kotlin, it does not implicitly reference an instance of the enclosing class.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains default nesting, hidden outer references, serialization consequences, and the inner modifier through Java and Kotlin examples.
Examples
Uses serializable View state, Java ButtonState, Kotlin ButtonState, and a direct nested-versus-inner correspondence table.
What it assumes
Assumes basic classes and interfaces, then establishes the Java-to-Kotlin difference from the nested-class default.
What you can do after
Apply it via Kotlin by declaring a default nested class or adding inner when enclosing-instance access is necessary.
How it connects
Relates nested classes to inner classes, enclosing classes, Java static nested classes, and serialization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.