Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An inner class in Kotlin is a class declared within another class and explicitly marked with the inner keyword, granting it an implicit reference to the instantiated object of its enclosing outer class. Because of this reference, an inner class can access all members of its outer class, including those marked with the private visibility modifier. In Kotlin, a class declared inside another class is by default a nested class, which behaves like a static nested class in Java and holds no reference to the outer class. The inner modifier is strictly required to establish an instance-level relationship.

Syntax and Instantiation

Because an inner class requires a reference to an instance of the outer class, it cannot be instantiated independently. You must first instantiate the outer class, and then use that instance to construct the inner class.
class OuterClass {
    private val outerState: String = "Enclosing state"

    inner class InnerClass {
        fun readOuterState(): String {
            // Direct access to private member of the outer class
            return outerState 
        }
    }
}

// Instantiation requires an outer instance
val outer = OuterClass()
val inner = outer.InnerClass()

Shadowing and Qualified this

If the inner class declares a property or function with the same name as a member in the outer class, the inner class member shadows the outer class member. To access the shadowed member of the outer class, Kotlin uses a qualified this expression with a label corresponding to the outer class name (this@OuterClassName).
class Outer {
    val sharedName: String = "Outer Property"

    inner class Inner {
        val sharedName: String = "Inner Property"

        fun printProperties() {
            // Refers to the Inner class property
            println(this.sharedName) 
            
            // Refers to the Outer class property via qualified 'this'
            println(this@Outer.sharedName) 
        }
    }
}

Technical Implications

  • Memory Overhead: Every instance of an inner class contains a hidden, implicit pointer to its outer class instance. This increases the memory footprint of the inner class compared to a standard nested class.
  • Garbage Collection: The implicit reference prevents the outer class instance from being garbage collected as long as the inner class instance remains strongly reachable.
  • Inheritance: An inner class can extend other classes and implement interfaces independently of its outer class. If an inner class inherits from a superclass that has members conflicting with the outer class, the qualified this syntax is required to resolve the ambiguity.
Master Kotlin with Deep Grasping Methodology!Learn More