0Pricing
Kotlin Academy · Lesson

Inner Classes

Access outer scope.

The inner Keyword

Marking a nested class inner gives it a reference to the outer instance, so it can access the outer class(rsquo)s members.

class Outer {
    val msg = "Hello"
    inner class Inner {
        fun show() = msg
    }
}

fun main() {
    println(Outer().Inner().show())
}

Creating an Inner Instance

Because an inner class needs an outer instance, you create it from one: Outer().Inner().

class Engine {
    val power = 100
    inner class Turbo {
        fun boosted() = power * 2
    }
}

fun main() {
    println(Engine().Turbo().boosted())
}

All lessons in this course

  1. Nested Classes
  2. Inner Classes
  3. Anonymous Objects
  4. Local Classes
← Back to Kotlin Academy