Nested and Inner Classes

Classes can be nested in other classes:

  1. class Outer {
  2. private val bar: Int = 1
  3. class Nested {
  4. fun foo() = 2
  5. }
  6. }
  7. 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.

  1. interface OuterInterface {
  2. class InnerClass
  3. interface InnerInterface
  4. }
  5. class OuterClass {
  6. class InnerClass
  7. interface InnerInterface
  8. }

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:

  1. class Outer {
  2. private val bar: Int = 1
  3. inner class Inner {
  4. fun foo() = bar
  5. }
  6. }
  7. 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:

  1. window.addMouseListener(object : MouseAdapter() {
  2. override fun mouseClicked(e: MouseEvent) { ... }
  3. override fun mouseEntered(e: MouseEvent) { ... }
  4. })

Note: on the JVM, if the object is an instance of a functional Java interface (i.e. a Java interface with a single abstract method), you can create it using a lambda expression prefixed with the type of the interface:

  1. val listener = ActionListener { println("clicked") }