Nested and inner classes

Classes can be nested in other classes:

class Outer { private val bar: Int = 1 class Nested { fun foo() = 2 } } val demo = Outer.Nested().foo() // == 2 

You can also use interfaces with nesting. All combinations of classes and interfaces are possible: You can nest interfaces in classes, classes in interfaces, and interfaces in interfaces.

interface OuterInterface { class InnerClass interface InnerInterface } class OuterClass { class InnerClass interface InnerInterface } 

Inner classes

A nested class marked as inner can access the members of its outer class. Inner classes carry a reference to an object of an outer class:

class Outer { private val bar: Int = 1 inner class Inner { fun foo() = bar } } val demo = Outer().Inner().foo() // == 1 

See Qualified this expressions to learn about disambiguation of this in inner classes.

Anonymous inner classes

Anonymous inner class instances are created using an object expression:

window.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { ... } override fun mouseEntered(e: MouseEvent) { ... } }) 
Last modified: 11 February 2021

© 2010–2021 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/docs/nested-classes.html