[英]What is best way to communicate parent class and its inner class in kotlin?
In java if I am having a class and inside it I have another child class, than child class can access its parent class methods, but while same is giving error in kotlin for example
class A {
static int methodSum(int a, int b) {
return a+b;
}
static final class Try {
void tryPrint() {
System.Out.println(methodSum(2,3).toString())
}
}
}
但同樣我無法在 Kotlin 中實現它給我的錯誤。 實現這一目標的最佳方法是什么。
請參閱 Kotlin 文檔中的嵌套和內部類。 當您使用“內部類”時,class 將始終持有對外部 class 的 object 的引用。
class Outer {
private val bar: Int = 1
inner class Inner {
fun getOuter() = this@Outer
fun foo() = bar
}
}
val outerObj = Outer().Inner().getOuter()
val bar = Outer().Inner().foo()
更新:因為 gidds 在他的評論中完美地解釋了這一點:
澄清一下:像 Java 一樣,Kotlin 提供內部類(引用外部類的實例)和嵌套類(不提供)。 但它們的默認值不同: Java 假定內部 class 除非您使用 static 將其標記為嵌套; 而 Kotlin 假定嵌套的 class 除非你用內部標記它。
像這樣使用內部 class
internal object A {
fun methodSum(a: Int, b: Int): Int {
return a + b
}
internal class Try {
fun tryPrint() {
println(methodSum(2, 3).toString())
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.