Kotlin 嵌套类和内部类

文章目录

嵌套类

在类的内部可以定义其他的类,这是类结构上的嵌套(Nested)。

kt 复制代码
class Container {
    val name = "Container"

    class NestedClass {
        fun getter() {
            // 此时无法访问外部类的成员
            // name
        }
    }
}

Note:接口也能嵌套。

内部类

内部类同样位于类内部,使用inner修饰。除了结构上嵌套外,内部类还能访问外部类的成员。

kt 复制代码
class Container {
    val name = "Container"

    inner class InnerClass {
        fun getter() {
            // 此时可以访问外部类的成员
            name
        }
    }
}

内部类只能使用外部类的对象调用实例化(普通嵌套类此限制):

kt 复制代码
fun main() {
    // Container.InnerClass() 不能使用
    Container().InnerClass()
}
相关推荐
码农哈丁2 小时前
从 JVM 到 Cargo:把整个 Kotlin 项目移植到 Rust 的踩坑实录
jvm·rust·kotlin
Kapaseker5 小时前
写过 4000 行 ViewModel 后,我开始这样拆 Compose 页面
android·kotlin
新时代牛马18 小时前
cyclictest 毛刺从哪来?从ftrace、latencytop、perf到IRQ/调度延迟定位
android·开发语言·python·kotlin
光电的一只菜鸡20 小时前
为什么调整LSC会对AF产生影响
android·开发语言·kotlin
hai_android21 小时前
FusibleFlow:Kotlin Flow 的融合机制原理
android·kotlin
alexhilton1 天前
从零开始的架构测试套件
android·kotlin·android jetpack
YB13751 天前
kotlin 关键字data
kotlin
YB13753 天前
kotlin 关键字expect/actual的作用
kotlin
Android打工仔3 天前
不要再把 Flow 当作一个容器
android·kotlin
天空之城--4 天前
Android行业一周动态:编码趋势与行业资讯汇总
android·性能优化·架构·kotlin·android jetpack