Kotlin Inner Classes

htt‮w//:sp‬ww.theitroad.com

In Kotlin, an inner class is a class that is defined inside another class and has access to 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 in Kotlin:

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.

To create an instance of the InnerClass, we first need to create an instance of the OuterClass:

val outer = OuterClass()
val inner = outer.InnerClass()
inner.printOuterName() // prints "Outer"

In this example, we create an instance of the OuterClass called outer, and then we create an instance of the InnerClass called inner using the outer instance. Finally, we call the printOuterName method of the InnerClass, which prints the name property of the OuterClass.

Inner classes are often used to encapsulate related functionality within a class, or to implement interfaces or abstract classes within a class.