Junior — Middle
What is the role of dividing classes into inner and nested classes, and what is it used for?
sobes.tech AI
Answer from AI
In Kotlin, there are two types of nested classes: nested and inner classes.
-
Nested class — a class declared inside another class without the
innerkeyword. Such a class does not have a reference to an instance of the outer class and cannot access its members directly. -
Inner class — declared with the
innerkeyword. It contains an implicit reference to an instance of the outer class and can access its properties and methods.
Role and application:
- Nested classes are used for logical grouping of classes that are closely related to the outer class but do not require access to its instance.
- Inner classes are used when the nested class needs access to the state of the outer object.
Example:
class Outer {
private val outerData = "Outer class data"
class Nested {
fun nestedFunction() = "Nested class"
}
inner class Inner {
fun innerFunction() = "Inner class and access to: $outerData"
}
}
fun main() {
val nested = Outer.Nested()
println(nested.nestedFunction()) // Nested class
val inner = Outer().Inner()
println(inner.innerFunction()) // Inner class and access to: Outer class data
}
Thus, the distinction helps manage scope and the relationship between classes, improving code organization.