What is Nested Class in Kotlin: Explanation and Example
nested class is a class defined inside another class without the inner keyword. It does not hold a reference to the outer class and behaves like a static class in other languages.How It Works
A nested class in Kotlin is like a small box placed inside a bigger box. The smaller box (nested class) lives inside the bigger box (outer class) but does not know anything about the bigger box's contents unless explicitly told. This means the nested class cannot access the outer class's properties or functions directly.
Think of it as a separate tool stored inside a toolbox. The tool is related to the toolbox but works independently. In Kotlin, nested classes are static by default, so they don't carry any extra baggage from the outer class, making them lightweight and easy to use when you want to group related classes together.
Example
This example shows a nested class inside an outer class. The nested class can be created and used without an instance of the outer class.
class Outer { class Nested { fun greet() = "Hello from Nested class" } } fun main() { val nested = Outer.Nested() println(nested.greet()) }
When to Use
Use nested classes when you want to logically group classes that belong together but don't need to access the outer class's members. This helps keep your code organized and clear.
For example, if you have a class representing a library, you might nest classes for different types of books or sections inside it. Since these nested classes don't need to know about the library's current state, making them nested keeps them simple and independent.
Key Points
- Nested classes do not have access to outer class members.
- They behave like static classes in other languages.
- Use them to group related classes without creating dependencies.
- To access outer class members, use
innerclasses instead.