Middle
What are nested and inner classes in Kotlin?
sobes.tech AI
Answer from AI
A nested class does not have access to the members of the outer class. It is simply a class declared inside another.
class Outer {
private val outerParameter = 1
class Nested {
fun printSomething() {
// Compilation error: Cannot access 'outerParameter': it is private in 'Outer'
// println(outerParameter)
println("Hello from nested class")
}
}
}
An inner class has access to the members of the outer class, including private ones. This is achieved using the inner keyword. An instance of an inner class is always associated with an instance of the outer class.
class Outer {
private val outerParameter = 1
inner class Inner {
fun printSomething() {
// Access to outer class member
println("Outer parameter is $outerParameter")
println("Hello from inner class")
}
}
}
Main differences:
| Feature | Nested Class | Inner Class |
|---|---|---|
| Access to outer | No | Yes (through an instance of the outer class) |
| Relationship with instance | Not linked to an instance of the outer class | Linked to an instance of the outer class |
| Declaration | Does not require a keyword (default is nested) | Requires the inner keyword |
| Usage | Can be used as a static equivalent (in Java context) | Cannot be static |
| Instance creation | Outer.Nested() |
Outer().Inner() |