gpt4 book ai didi

kotlin - 在 Kotlin 中,为什么我不能在内部类的实例上访问外部类?

转载 作者:行者123 更新时间:2023-12-01 15:16:06 25 4
gpt4 key购买 nike

为什么我不能在内部类的实例上访问外部类的属性?

class A(val id: String) {

inner class B {}
}

fun test() {
val a = A("test")
val b = a.B()
aid(a)
bid(b)
}

fun aid(a:A): String = a.id
fun bid(b:A.B): String = b.id //Unresolved reference: id

在此示例中,b.id 无法编译。

我认为我必须在 B 上添加一个返回 this@A.id 的 setter/getter .但为什么?

最佳答案

内部类仅具有对封闭实例的引用,因此不继承外部类的成员。

由于内部类具有对封闭类的引用,因此只能在类中访问此封闭实例(Java:Outer.this,Kotlin:this@Outer),但是您不能从内部外部访问封闭实例是正确的类(class)。

A class may be marked as inner to be able to access members of outer class.
Kotlin Reference / Nested and Inner Classes



使您自己的 getter 函数返回封闭实例是 the only way去做这个。

虽然生成的对外部实例的引用是包私有(private)的 according to Jon Skeet , Java 和 Kotlin 都没有任何方法来获取这个实例。您可以使用反射,但由于生成的字段名称可能不可靠,您最好的选择是修改内部类。

关于kotlin - 在 Kotlin 中,为什么我不能在内部类的实例上访问外部类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52088622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com