What is Inner Class in Kotlin: Explanation and Example
inner class is a nested class that holds a reference to an instance of its outer class. It allows the inner class to access members of the outer class directly using this@OuterClass.How It Works
Imagine you have a house (outer class) and a room inside it (inner class). The room can easily access things in the house, like the electricity or water supply. Similarly, an inner class in Kotlin is a class defined inside another class that keeps a connection to the outer class instance.
This connection means the inner class can use the outer class’s properties and functions directly. Without the inner keyword, a nested class cannot access the outer class’s members because it does not hold a reference to the outer class instance.
In Kotlin, you declare an inner class by adding the inner keyword before the class name inside the outer class. This makes the inner class aware of the outer class instance it belongs to.
Example
This example shows an outer class Car with an inner class Engine. The inner class accesses the outer class's property model.
class Car(val model: String) { inner class Engine { fun start() { println("Starting engine of $model") } } } fun main() { val car = Car("Toyota") val engine = car.Engine() engine.start() }
When to Use
Use an inner class when you want a nested class to work closely with its outer class instance. This is useful when the inner class needs to access or modify the outer class’s properties or call its functions.
For example, in a user interface, an inner class might represent a button inside a window, and it needs to update the window’s state. Or in a game, an inner class could represent a part of a character that depends on the character’s overall status.
Key Points
- An
inner classkeeps a reference to its outer class instance. - It can access outer class members directly.
- Declared with the
innerkeyword inside the outer class. - Without
inner, nested classes cannot access outer class properties.