Kotlin Nested Classes
In Kotlin, a nested class is a class that is defined inside another class. A nested class can be used to group related classes together, or to encapsulate the functionality of a class within another class.
There are two types of nested classes in Kotlin: inner classes and static nested classes.
An inner class is a class that has a reference to an instance of its outer class. An inner class can access the members of its outer class, even if they are private. To define an inner class, you use the inner
keyword. Here's an example of an inner class:
class OuterClass { private val name: String = "Outer" inner class InnerClass { fun printOuterName() { println(name) } } }
In this example, we define an inner class called InnerClass
inside the OuterClass
. The InnerClass
has access to the name
property of the OuterClass
, even though it is private. We can create an instance of the InnerClass
like this:
val outer = OuterClass() val inner = outer.InnerClass() inner.printOuterName() // prints "Outer"
A static nested class, on the other hand, is a class that does not have a reference to an instance of its outer class. A static nested class can access only the members of its outer class that are marked as public
or internal
. To define a static nested class, you simply define a class inside another class without using the inner
keyword. Here's an example of a static nested class:
class OuterClass { private val name: String = "Outer" class NestedClass { fun printOuterName() { // cannot access the name property println("Cannot access the name property") } } }
In this example, we define a static nested class called NestedClass
inside the OuterClass
. The NestedClass
does not have access to the name
property of the OuterClass
. We can create an instance of the NestedClass
like this:
val nested = OuterClass.NestedClass() nested.printOuterName() // prints "Cannot access the name property"
Note that if you do not specify whether a nested class is inner or static, it defaults to static.