Kotlin 嵌套类和内部类

Kotlin 嵌套类

与 Java 类似,Kotlin 允许你在一个类中定义另一个类,称为嵌套类。

class Outer {
    ... .. ...
    class Nested {
        ... .. ...
    }
}

由于 Nested 类是其包含类 Outer 的成员,你可以使用 . 符号来访问 Nested 类及其成员。


示例:Kotlin 嵌套类

class Outer {

    val a = "Outside Nested class."

    class Nested {
        val b = "Inside Nested class."
        fun callMe() = "Function call from inside Nested class."
    }
}

fun main(args: Array<String>) {
    // accessing member of Nested class
    println(Outer.Nested().b)

    // creating object of Nested class
    val nested = Outer.Nested()
    println(nested.callMe())
}

运行程序后,输出将是

Inside Nested class.
Function call from inside Nested class.

面向 Java 用户

Kotlin 中的嵌套类类似于 Java 中的静态嵌套类。

在 Java 中,当你在一个类内部声明一个类时,它默认会成为一个内部类。然而在 Kotlin 中,你需要使用 inner 修饰符来创建一个内部类,我们将在下一节进行讨论。


Kotlin 内部类

Kotlin 中的嵌套类无法访问外部类的实例。例如:

class Outer {
    val foo = "Outside Nested class."

    class Nested {
        // Error! cannot access member of outer class.
        fun callMe() = foo
    }
}

fun main(args: Array<String>) {

    val outer = Outer()
    println(outer.Nested().callMe())
}

上面的代码无法编译,因为我们试图从 Nested 类内部访问 Outer 类的 foo 属性。

为了解决这个问题,你需要用 inner 修饰嵌套类来创建内部类。内部类会携带对外部类的引用,并可以访问外部类的成员。


示例:Kotlin 内部类

class Outer {

    val a = "Outside Nested class."

    inner class Inner {
        fun callMe() = a
    }
}

fun main(args: Array<String>) {

    val outer = Outer()
    println("Using outer object: ${outer.Inner().callMe()}")

    val inner = Outer().Inner()
    println("Using inner object: ${inner.callMe()}")
}

运行程序后,输出将是

Using outer object: Outside Nested class.
Using inner object: Outside Nested class.

推荐阅读: 匿名内部类

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战