0
0
Kotlinprogramming~3 mins

Why Inner classes and nested classes in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how grouping code inside classes can save you from messy, confusing programs!

The Scenario

Imagine you have a big box with smaller boxes inside it. To find something in a small box, you must open the big box first. Now, think about writing code where you want to organize related parts together, but you have to write everything separately and connect them manually.

The Problem

Writing all parts separately means you must remember to link them correctly every time. It's easy to make mistakes, and your code becomes messy and hard to understand. Changing one part might break others because they are not clearly grouped.

The Solution

Inner and nested classes let you keep related code together inside a bigger class. This way, the smaller classes can access the bigger class's data easily (if inner), or stay independent but grouped (if nested). It makes your code cleaner, easier to read, and safer to change.

Before vs After
Before
class Car {
  val brand = "Toyota"
}

class Engine {
  fun start() = println("Engine started")
}
After
class Car {
  val brand = "Toyota"
  inner class Engine {
    fun start() = println("${brand} engine started")
  }
}
What It Enables

You can organize complex code clearly, letting smaller parts access or stay separate from the bigger part, making your programs easier to build and maintain.

Real Life Example

Think of a smartphone app where a Screen class contains a Button class inside it. The Button can easily use Screen's settings if it's an inner class, or just be grouped inside Screen if it's nested, keeping everything neat and connected.

Key Takeaways

Inner and nested classes help group related code inside a bigger class.

Inner classes can access the outer class's data; nested classes cannot.

This makes code cleaner, easier to understand, and safer to change.