Inner and nested classes help organize code by grouping related classes together inside another class.
Inner classes and nested classes in Kotlin
class Outer { class Nested { // Nested class code } inner class Inner { // Inner class code } }
A nested class does not have access to the outer class's members.
An inner class can access the outer class's members and needs the inner keyword.
class Outer { class Nested { fun greet() = "Hello from Nested" } }
name property.class Outer(val name: String) { inner class Inner { fun greet() = "Hello from Inner, outer name is $name" } }
This program shows how to create and use nested and inner classes. The nested class cannot access the outer class's name, but the inner class can.
class Outer(val name: String) { class Nested { fun greet() = "Hello from Nested" } inner class Inner { fun greet() = "Hello from Inner, outer name is $name" } } fun main() { val nested = Outer.Nested() println(nested.greet()) val outer = Outer("Kotlin") val inner = outer.Inner() println(inner.greet()) }
Use inner keyword only when the inner class needs to access outer class members.
Nested classes are like static classes in other languages; they don't hold a reference to the outer class.
Inner classes hold a reference to the outer class instance, so be careful to avoid memory leaks.
Nested classes are defined inside another class but cannot access its members.
Inner classes use the inner keyword and can access outer class members.
Use inner classes when you need to work closely with the outer class's data.