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.

A nested class in Kotlin is a class declared within the lexical scope of another class. By default, nested classes are statically bound, meaning they do not hold an implicit reference to an instance of their enclosing (outer) class. This behavior is structurally equivalent to a static nested class in Java. Because a nested class lacks a reference to the outer class instance, it cannot access the instance members (properties or functions) of the enclosing class. It operates entirely independently of the outer class’s state.

Syntax and Instantiation

To instantiate a nested class, you qualify the nested class name with the outer class name, treating the outer class purely as a namespace. You do not need to instantiate the outer class first.
class Outer {
    private val outerInstanceProperty: String = "Outer State"

    class Nested {
        fun printMessage() {
            println("Executing inside the nested class.")
            
            // The following line would cause a compilation error:
            // println(outerInstanceProperty) 
        }
    }
}

// Instantiation requires the Outer class name as a qualifier, 
// but does NOT require an instance of Outer.
val nestedObject = Outer.Nested()
nestedObject.printMessage()

Nesting Interfaces

Kotlin allows interfaces to be nested within classes, and classes to be nested within interfaces. By definition, all nested interfaces and classes nested within interfaces are implicitly static.
class Outer {
    interface NestedInterface {
        fun execute()
    }
}

// Implementing a nested interface
class Implementation : Outer.NestedInterface {
    override fun execute() {
        println("Implemented nested interface")
    }
}

Contrast with Inner Classes

To alter the default static binding of a nested class so that it can access the outer class’s instance members, the nested class must be explicitly modified with the inner keyword. Marking a class as inner changes its memory footprint and instantiation mechanics. It forces the nested class to hold a reference to the outer class instance, meaning the nested class can no longer be instantiated without first creating an instance of the outer class.
class Outer {
    private val outerState: String = "Outer State"

    // 'inner' keyword changes the class from statically nested to an inner class
    inner class Inner {
        fun accessOuter() {
            // Access to outer class members is now permitted
            println(outerState) 
        }
    }
}

// Instantiation now requires an instance of the Outer class
val outerInstance = Outer()
val innerObject = outerInstance.Inner()
Master Kotlin with Deep Grasping Methodology!Learn More