0
0
Kotlinprogramming~5 mins

Inner class access to outer members in Kotlin

Choose your learning style9 modes available
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.
When you want a small helper class to work closely with its outer class data.
When you want to organize code by grouping related classes inside one another.
When the inner class needs to change or read the outer class's properties.
When you want to avoid passing outer class data explicitly to the inner class.
When you want to keep the inner class hidden from other parts of the program.
Syntax
Kotlin
class Outer {
    private val outerProperty = "Hello"

    inner class Inner {
        fun greet() = outerProperty
    }
}
Use the keyword inner before the class name to make it an inner class that can access outer class members.
Without inner, the nested class cannot access outer class properties or functions.
Examples
Inner class can access the private property message of the outer class.
Kotlin
class Outer {
    private val message = "Hi from Outer"

    inner class Inner {
        fun showMessage() = message
    }
}
Nested class without inner cannot access outer class properties.
Kotlin
class Outer {
    val number = 10

    class Nested {
        fun getNumber() = "Cannot access number"
    }
}
Inner class accessing outer class property and printing it.
Kotlin
class Outer {
    val text = "Outer Text"

    inner class Inner {
        fun printText() {
            println(text)
        }
    }
}

fun main() {
    val outer = Outer()
    val inner = outer.Inner()
    inner.printText()
}
Sample Program
This program shows how the inner class accesses the outer class's private property and prints it.
Kotlin
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())
}
OutputSuccess
Important Notes
The inner keyword is required to access outer class members from the inner class.
You can create an inner class instance only from an instance of the outer class.
Inner classes hold a reference to their outer class instance.
Summary
Inner classes use the inner keyword to access outer class members.
They help keep related code together and share data easily.
Without inner, nested classes cannot see outer class properties.