Sobes.tech
Junior — Middle

What is the difference between an inner class declaration and a nested class in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, there are two types of classes nested within another class: nested class and inner class.

  • Nested class — a class declared inside another class without the inner keyword. Such a class does not have access to the members of the outer class.

  • Inner class — declared with the inner keyword. It holds a reference to an instance of the outer class and can access its properties and methods.

Example:

class Outer {
    private val bar: Int = 1

    class Nested {
        fun foo() = 2
    }

    inner class Inner {
        fun foo() = bar
    }
}

fun main() {
    val nested = Outer.Nested()
    println(nested.foo()) // 2

    val inner = Outer().Inner()
    println(inner.foo()) // 1
}

Here, Nested does not have access to bar, but Inner does.