Introduction
Inner classes can use variables and functions from their outer class. This helps keep related code together and makes it easier to work with shared data.
class Outer { private val outerProperty = "Hello" inner class Inner { fun greet() = outerProperty } }
message of the outer class.class Outer { private val message = "Hi from Outer" inner class Inner { fun showMessage() = message } }
inner cannot access outer class properties.class Outer { val number = 10 class Nested { fun getNumber() = "Cannot access number" } }
class Outer { val text = "Outer Text" inner class Inner { fun printText() { println(text) } } } fun main() { val outer = Outer() val inner = outer.Inner() inner.printText() }
class Outer { private val greeting = "Hello from Outer" inner class Inner { fun greet() = greeting } } fun main() { val outer = Outer() val inner = outer.Inner() println(inner.greet()) }
inner allows the nested class to hold a reference to the outer class and access its members.inner for access [OK]name?inner keyword can access outer class properties directly.inner and accesses name correctly. class Outer { val name = \"Kotlin\"; class Inner { fun printName() = println(name) } } lacks inner. class Outer { val name = \"Kotlin\"; nested class Inner { fun printName() = println(name) } } uses invalid nested keyword. class Outer { val name = \"Kotlin\"; inner class Inner { fun printName() = println(this.name) } } tries to access this.name which refers to inner class, not outer.inner and direct property name [OK]class Outer(val x: Int) {
inner class Inner {
fun printX() = println(x)
}
}
fun main() {
val outer = Outer(10)
val inner = outer.Inner()
inner.printX()
}x because it is declared with inner.Outer object is created with x=10. The inner class instance calls printX() which prints x value 10.class Outer {
val message = "Hello"
class Inner {
fun greet() = println(message)
}
}inner keyword cannot access outer class properties.Inner class tries to print message but cannot see it, causing a compilation error.class Outer(val number: Int) {
inner class Inner {
fun multiply(factor: Int) = number * factor
}
}
fun main() {
val outer = Outer(5)
val inner = outer.Inner()
println(inner.multiply(3))
}number because it is declared with inner. The method multiplies number by the given factor.Pass the test and this pattern moves unknown