liveBook · Manning

Inner class

As explained in Kotlin in Action, 2E

An inner class is a class declared inside another class and associated with an instance of the containing class.

An inner class is declared inside another class and retains a reference to an instance of the outer class. Kotlin keeps nested classes independent by default; add inner when outer-instance access is required. section 4.1.4 section 4.6

Making outer access explicit

class Outer { inner class Inner { fun getOuterReference(): Outer = this@Outer } } Here, inner makes Inner retain an Outer reference, and this@Outer identifies the enclosing instance. Without inner, Kotlin's nested class resembles Java's static nested class. section 4.1.4

Serializable view state

interface State : Serializable class Button : View { override fun getCurrentState(): State = ButtonState() override fun restoreState(state: State) { /* ... */ } class ButtonState : State { /* ... */ } } ButtonState is deliberately nested rather than inner, so it does not capture Button implicitly. In Java, the equivalent class is inner by default; that hidden reference can cause serialization to fail when Button is not serializable. section 4.1.4

Table 4.3 Correspondence between nested and inner classes in Java and Kotlin (view table figure)

Class A declared within another class B

In Java

In Kotlin

Nested class (doesn’t store a reference to an outer class)

static class A

class A

Inner class (stores a reference to an outer class)

class A

inner class A

Use the correspondence table to compare Java's static and ordinary nested-class forms with Kotlin's nested and inner modifiers. section 4.1.4

How Kotlin in Action, 2E covers it

How deep it goes
Explains implicit references, serialization consequences, Java/Kotlin defaults, and this@Outer access, but stops short of broader class hierarchies.
Examples
Uses a serializable ButtonState example, a Java Button implementation, and a Kotlin Outer/Inner reference example.
What it assumes
Assumes basic classes and interfaces, while establishing nested-versus-inner behavior from Kotlin's default rules.
What you can do after
Evaluate whether a Kotlin nested declaration should capture its outer instance and select nested or inner syntax accordingly.
How it connects
Connects inner classes with nested classes, outer-class references, serialization, and Java static nested classes.

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.