class Outer { private val outerVal = "Outer" class Nested { fun nestedFun() = "Nested" } inner class Inner { fun innerFun() = outerVal } } fun main() { val nested = Outer.Nested() val inner = Outer().Inner() println(nested.nestedFun()) println(inner.innerFun()) }
The Nested class is static and cannot access outerVal. It returns "Nested". The Inner class is an inner class and can access outerVal, so it returns "Outer".
Inner classes hold a reference to an instance of the outer class and can access its members. Nested classes are static and cannot access outer class members.
class Container(val name: String) { inner class Content { fun printName() = println(name) } } fun main() { val container = Container("Box") val content = container.Content() content.printName() }
The inner class Content can access the name property of Container because it holds a reference to the outer class instance.
class Example { private val value = 10 class Nested { fun getValue() = value } } fun main() { val nested = Example.Nested() println(nested.getValue()) }
The nested class is static and cannot access the instance property value. This causes a compilation error for unresolved reference.
Inner classes keep a reference to the outer class instance, which can increase memory usage if many inner class instances exist. Nested classes are static and do not hold such references.