0Pricing
Kotlin Academy · Lesson

Local Classes

Classes in functions.

Classes in Functions

Kotlin lets you declare a local class inside a function body. It is visible only within that function.

fun main() {
    class Greeting(val text: String) {
        fun show() = println(text)
    }
    Greeting("Hello local").show()
}

Scoped to the Function

A local class cannot be used outside the function where it is declared, keeping helper types tightly contained.

fun build(): String {
    class Builder {
        fun make() = "built"
    }
    return Builder().make()
}

fun main() {
    println(build())
}

All lessons in this course

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