Nested classes

suggest change

A class declared inside another class (or interface, or function) is a nested class. Kotlin has several kinds of them, and the main difference between them is whether they hold a reference to an instance of the enclosing class:

Kotlin's default is the opposite of Java's. In Java a nested class is "inner" unless you write static. In Kotlin a nested class is "static" unless you write inner. That way you don't hold a hidden reference to the outer object unless you ask for one.

Nested classes

A plain nested class is only placed in the namespace of the outer class. You refer to it as Outer.Nested and create it without an Outer instance:

class Outer {
    private val secret = 42

    class Nested {
        fun describe() = "I'm Nested, I don't know any Outer instance"

        // a nested class can access private members of Outer,
        // but it needs an Outer instance to do so
        fun peek(o: Outer) = o.secret
    }
}

fun main() {
    val n = Outer.Nested()   // no Outer instance needed
    println(n.describe())
    println(n.peek(Outer()))
}
I'm Nested, I don't know any Outer instance
42

A nested class is inside the scope of the outer class, so it can see the outer class's private members. It has no this of the outer class, though. Using an outer property directly is a compile error:

class Outer {
    val x = 1

    class Nested {
        fun foo() = x
    }
}
b1.kt:5:21: error: outer class 'class Outer : Any' of non-inner class cannot be used as receiver.
        fun foo() = x
                    ^

Access in the other direction is more restricted: the outer class can not see private members of a nested class. Kotlin's private means "visible inside this class", and the outer class is not inside the nested one:

class Outer {
    class Nested {
        private val hidden = "nested secret"
    }

    fun read(n: Nested) = n.hidden
}
a4.kt:6:29: error: cannot access 'val hidden: String': it is private in 'Outer.Nested'.
    fun read(n: Nested) = n.hidden
                            ^^^^^^

This differs from Java, where the outer class can read private fields of its nested classes. Use internal or leave the member public if the outer class needs it.

Inner classes

Mark a nested class inner and every instance of it is tied to an instance of the outer class. The inner class can then read and modify the outer object's properties and call its methods, including private ones:

class Counter(private val name: String) {
    private var count = 0

    inner class Clicker {
        fun click() {
            count++                      // modifies the outer instance
            println("$name: $count")
        }
    }
}

fun main() {
    val c = Counter("visits")
    val a = c.Clicker()
    val b = c.Clicker()
    a.click()
    b.click()
    a.click()

    val other = Counter("downloads").Clicker()
    other.click()
}
visits: 1
visits: 2
visits: 3
downloads: 1

You create an inner class through an outer instance: c.Clicker(). Both a and b share the same Counter, so they update the same count. Outer.Clicker() without an instance doesn't compile.

this@Outer: qualified this

Inside an inner class, this is the inner instance. When names clash, or when you need the outer object itself, use a qualified this with the outer class name as label:

class Window(val title: String) {
    val width = 800

    inner class Button(val title: String) {
        val width = 120

        fun describe() {
            println("button title: $title")             // Button.title
            println("button title: ${this.title}")      // same
            println("window title: ${this@Window.title}")
            println("width: $width, window width: ${this@Window.width}")
        }

        fun window(): Window = this@Window
    }
}

fun main() {
    val w = Window("Settings")
    val ok = w.Button("OK")
    ok.describe()
    println(ok.window() === w)
}
button title: OK
button title: OK
window title: Settings
width: 120, window width: 800
true

Name lookup goes from the innermost scope outward: width is the button's, and you need this@Window.width to reach the window's.

In the same way, super@Outer calls the outer class's superclass implementation of a method:

open class Base {
    open fun greet() = "Base"
}

class Outer : Base() {
    override fun greet() = "Outer"

    inner class Inner {
        fun test() {
            println(greet())               // Outer.greet()
            println(super@Outer.greet())   // Base.greet() called on the outer instance
        }
    }
}

fun main() {
    Outer().Inner().test()
}
Outer
Base

Generic outer classes

An inner class can use the type parameters of its outer class, because every inner instance belongs to a specific Box<T>. A nested class can't, since it isn't tied to any Box and so has no T:

class Box<T>(val items: MutableList<T>) {
    inner class Cursor {
        var pos = 0
        fun next(): T = items[pos++]     // T from Box is visible
    }

    class Empty {
        // fun first(): T  -- error: T is not visible in a nested class
    }

    class Wrapper<U>(val value: U)        // nested classes declare their own
}

fun main() {
    val box = Box(mutableListOf("a", "b", "c"))
    val cur: Box<String>.Cursor = box.Cursor()
    println(cur.next() + cur.next())
    val w = Box.Wrapper(3.14)
    println(w.value)
}
ab
3.14

The full type of an inner instance includes the outer type's arguments: Box<String>.Cursor.

What inner classes can't contain

An inner class can't declare nested (non-inner) classes, objects or a companion object. Those would be "static" members, and an inner class is always tied to an instance:

class Outer {
    inner class Inner {
        class Deep
        object Obj
        companion object
    }
}
b2.kt:3:9: error: 'Class' is prohibited here.
        class Deep
        ^^^^^^^^^^
b2.kt:4:9: error: 'Object' is prohibited here.
        object Obj
        ^^^^^^^^^^
b2.kt:5:19: error: 'Companion object' is prohibited here.
        companion object
                  ^^^^^^

Inner classes inside inner classes are allowed. Put shared nested types in the outer class instead.

What the compiler generates

On the JVM both kinds compile to a separate class file named Outer$Nested.class. Compile this:

class Outer {
    class Nested
    inner class Inner
}

and inspect it with javap -p:

public final class Outer$Nested {
  public Outer$Nested();
}

public final class Outer$Inner {
  final Outer this$0;
  public Outer$Inner(Outer);
}

The inner class gets a hidden field this$0 holding the outer instance and a constructor that takes it. c.Clicker() is really Counter$Clicker(c). That is where this@Counter comes from.

From Java, a Kotlin nested class looks like a static nested class and an inner class looks like a Java inner class:

class Shapes {
    val name = "shapes"
    class Point(val x: Int, val y: Int)
    inner class Label(val text: String) {
        fun full() = "$name/$text"
    }
}
public class Main {
    public static void main(String[] args) {
        Shapes.Point p = new Shapes.Point(1, 2);   // static nested class in Java terms
        Shapes s = new Shapes();
        Shapes.Label l = s.new Label("title");     // inner class needs an outer instance
        System.out.println(p.getX() + "," + p.getY() + " " + l.full());
    }
}
1,2 shapes/title

Inner classes keep the outer object alive

That hidden this$0 reference means that as long as an inner object is reachable, its outer object is too. If an inner object ends up somewhere long-lived (a global job queue, a listener registry, a cache), the outer object can't be garbage collected:

import java.lang.ref.WeakReference

class Screen {
    val pixels = ByteArray(50_000_000)          // something big

    inner class InnerTask : Runnable {
        override fun run() = println("inner task")
    }

    class NestedTask : Runnable {
        override fun run() = println("nested task")
    }
}

val longLived = mutableListOf<Runnable>()       // e.g. a global job queue

fun isCollected(makeTask: (Screen) -> Runnable): Boolean {
    var screen: Screen? = Screen()
    val ref = WeakReference(screen)
    longLived += makeTask(screen!!)
    screen = null
    repeat(3) { System.gc(); Thread.sleep(50) }
    return ref.get() == null
}

fun main() {
    println("screen collected with NestedTask queued: " + isCollected { Screen.NestedTask() })
    println("screen collected with InnerTask queued:  " + isCollected { it.InnerTask() })
}
screen collected with NestedTask queued: true
screen collected with InnerTask queued:  false

The queued InnerTask keeps its 50 MB Screen alive even though nothing else uses it. This is the classic Android leak where an inner Handler or AsyncTask holds on to an Activity. The rule: use a plain nested class by default, and add inner only when the class really needs the outer instance. If it only needs a value or two, pass them to the constructor. See Memory and garbage collection for more on reachability.

Local classes

A class can be declared inside a function. It is visible only in that function, and like a lambda it can read and modify the function's local variables:

fun parseAll(lines: List<String>): List<String> {
    var errors = 0

    // a local class: visible only inside parseAll
    class Entry(val key: String, val value: String) {
        override fun toString() = "$key=$value"
    }

    fun parse(line: String): Entry? {
        val parts = line.split("=", limit = 2)
        if (parts.size != 2) {
            errors++          // local functions and classes can modify captured vars
            return null
        }
        return Entry(parts[0].trim(), parts[1].trim())
    }

    val entries = lines.mapNotNull(::parse)
    println("parsed ${entries.size}, errors: $errors")
    return entries.map { it.toString() }
}

fun main() {
    println(parseAll(listOf("a = 1", "garbage", "b=2", "c = x=y")))
}
parsed 3, errors: 1
[a=1, b=2, c=x=y]

Local classes are handy for a helper type that only one function uses. In practice a local data class or a Pair is more common than a full local class.

Anonymous classes: object expressions

An object expression declares an anonymous class and creates its single instance in one step. It can implement interfaces, extend a class, have its own state, and capture local variables:

fun interface Listener {
    fun onEvent(name: String)
}

class Button {
    private val listeners = mutableListOf<Listener>()
    fun addListener(l: Listener) { listeners += l }
    fun click() = listeners.forEach { it.onEvent("click") }
}

fun main() {
    var clicks = 0
    val button = Button()

    // object expression: an anonymous class, created on the spot
    button.addListener(object : Listener {
        private var seen = 0
        override fun onEvent(name: String) {
            seen++
            clicks++
            println("anonymous: $name #$seen")
        }
    })

    // for a fun interface, a lambda does the same job
    button.addListener { name -> println("lambda: $name") }

    button.click()
    button.click()
    println("total clicks: $clicks")
}
anonymous: click #1
lambda: click
anonymous: click #2
lambda: click
total clicks: 2

Use an object expression when you need more than one method, your own state, or a superclass. For a single-method fun interface, a lambda is shorter. An object expression created inside a class method that uses the class's members captures this of that class, so it keeps the outer object alive just like an inner class does.

An object expression with no supertype is useful as an ad-hoc grouping of values. Its members are accessible when the object is a local variable or a private property:

class Temperature(private val celsius: Double) {
    // the anonymous type is kept because the property is private
    private val formatter = object {
        fun c() = "%.1f C".format(celsius)
        fun f() = "%.1f F".format(celsius * 9 / 5 + 32)
    }

    fun show() = "${formatter.c()} / ${formatter.f()}"
}

fun main() {
    println(Temperature(21.5).show())
    val point = object {
        val x = 3
        val y = 4
    }
    println(point.x * point.x + point.y * point.y)
}
21.5 C / 70.7 F
25

If formatter were public, its type would be Any outside the class and c() would not be accessible.

Common uses of nested classes

Sealed hierarchies

Nesting the subtypes of a sealed class or interface groups them under one name and makes the call sites read well (Shape.Circle). Exhaustive when works the same way:

sealed interface Shape {
    data class Circle(val r: Double) : Shape
    data class Rect(val w: Double, val h: Double) : Shape
    data object Empty : Shape
}

fun area(s: Shape): Double = when (s) {
    is Shape.Circle -> Math.PI * s.r * s.r
    is Shape.Rect -> s.w * s.h
    Shape.Empty -> 0.0
}

fun main() {
    val shapes = listOf(Shape.Circle(1.0), Shape.Rect(2.0, 3.0), Shape.Empty)
    for (s in shapes) println("$s -> ${"%.2f".format(area(s))}")
}
Circle(r=1.0) -> 3.14
Rect(w=2.0, h=3.0) -> 6.00
Empty -> 0.00

More on sealed types in Polymorphism.

Builders

A nested Builder can call the outer class's private constructor, so the builder becomes the only way to create instances:

class HttpRequest private constructor(
    val method: String,
    val url: String,
    val headers: Map<String, String>,
) {
    override fun toString() = "$method $url $headers"

    class Builder(private val url: String) {
        private var method = "GET"
        private val headers = mutableMapOf<String, String>()

        fun method(m: String) = apply { method = m }
        fun header(name: String, value: String) = apply { headers[name] = value }

        // Builder is nested, so it can call the private constructor
        fun build() = HttpRequest(method, url, headers.toMap())
    }
}

fun main() {
    val req = HttpRequest.Builder("https://example.com/api")
        .method("POST")
        .header("Accept", "application/json")
        .build()
    println(req)
}
POST https://example.com/api {Accept=application/json}

With named and default arguments you rarely need builders in pure Kotlin code (see Named and optional parameters), but they are still common in APIs meant for Java callers.

Iterators and views

Iterators are a natural fit for a private inner class: they need the outer collection's data, and callers only see the Iterator interface:

class Ring(private val items: List<String>) : Iterable<String> {
    var iteratorsCreated = 0
        private set

    override fun iterator(): Iterator<String> = RingIterator()

    private inner class RingIterator : Iterator<String> {
        private var i = 0
        init { iteratorsCreated++ }
        override fun hasNext() = i < items.size * 2   // go around twice
        override fun next() = items[i++ % items.size]
    }
}

fun main() {
    val ring = Ring(listOf("a", "b", "c"))
    println(ring.joinToString(""))
    println(ring.take(4))
    println("iterators: ${ring.iteratorsCreated}")
}
abcabc
[a, b, c, a]
iterators: 2

Types nested in interfaces, enums in classes

Interfaces can contain nested classes, enums and other interfaces, and classes can contain interfaces. This is a good place for a default implementation or for types that only make sense together with their owner:

interface Cache {
    fun get(key: String): String?
    fun put(key: String, value: String)

    // nested class inside an interface
    class InMemory : Cache {
        private val map = HashMap<String, String>()
        override fun get(key: String) = map[key]
        override fun put(key: String, value: String) { map[key] = value }
    }

    enum class Policy { LRU, LFU, FIFO }
}

class Server {
    // nested interface inside a class
    interface Handler {
        fun handle(path: String): String
    }

    enum class State { STARTING, RUNNING, STOPPED }

    var state = State.STARTING
}

fun main() {
    val cache: Cache = Cache.InMemory()
    cache.put("k", "v")
    println(cache.get("k"))
    println(Cache.Policy.entries)

    val h = object : Server.Handler {
        override fun handle(path: String) = "handled $path"
    }
    println(h.handle("/index"))
    println(Server().state)
}
v
[LRU, LFU, FIFO]
handled /index
STARTING

Interfaces can't have inner classes, since an interface has no state for them to bind to.

Nested objects, companion objects and imports

An object declared inside a class is a nested singleton. A companion object is a special nested object whose members you can call through the class name alone. Both are nested, not inner: they don't belong to any instance. See Singleton objects for more.

Nested declarations can be imported like top-level ones, optionally renamed with as:

package shop

class Order(val id: Int) {
    enum class Status { NEW, PAID, SHIPPED }

    class Line(val sku: String, val qty: Int)

    companion object {
        fun sample() = Order(1)
    }

    object Validator {
        fun valid(o: Order) = o.id > 0
    }
}
import shop.Order
import shop.Order.Status
import shop.Order.Line as OrderLine

fun main() {
    val s = Status.PAID
    val line = OrderLine("book-42", 2)
    println("$s ${line.sku} x${line.qty}")
    println(Order.sample().id)            // companion: called through the class name
    println(Order.Validator.valid(Order(7)))  // nested object: needs its own name
}
PAID book-42 x2
1
true

Visibility of nested classes

Nested classes take the usual visibility modifiers (see Visibility Modifiers). A private nested class is visible only inside the outer class, which is good for implementation details. The compiler won't let a private type leak through a more visible API:

class Parser {
    private class Token(val text: String)

    // error: public function exposes its private-in-class type Token
    fun firstToken(input: String): Token = Token(input.substringBefore(' '))
}
e1.kt:5:9: error: 'public' function exposes its 'private-in-class' return type 'Token'.
    fun firstToken(input: String): Token = Token(input.substringBefore(' '))
        ^^^^^^^^^^

Either make the function private too, or return a public interface that the private class implements, as Ring.iterator() does above.

Choosing the right kind

Kind Syntax Outer instance Typical use
Nested class class A { class B } no builders, sealed subtypes, helper types, constants grouped by owner
Inner class class A { inner class B } yes (this@A) iterators, views, callbacks that must change outer state
Local class fun f() { class B } captures locals a helper type used by one function
Object expression object : I { ... } captures locals and this one-off implementations with several methods or state
Nested object class A { object B } no a singleton grouped under its owner

Start with a plain nested class. Make it inner only when it really needs the outer instance, and remember that the outer object then stays alive as long as the inner object does.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents