What is the Kotlin equivalent of Java's OuterClass.super.method()
?
Example (in Java):
class Outer {
class Inner {
void someMethod() {
Outer.super.someOtherMethod();
}
}
@Override
public String someOtherMethod() {
// This is not called...
}
}
No, you cannot assume that the outer class holds an instance of the inner class; but that's irrelevant to the question. You're first question (whether the inner class holds an instance of the outer class) was the relevant question; but the answer is yes, always.
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.
Function call from inside Nested class. The nested class in Kotlin is similar to static nested class in Java. In Java, when you declare a class inside another class, it becomes an inner class by default. However in Kotlin, you need to use inner modifier to create an inner class which we will discuss next.
Use the [email protected]()
syntax:
open class C {
open fun f() { println("C.f()") }
}
class D : C() {
override fun f() { println("D.f()") }
inner class X {
fun g() {
[email protected]() // <- here
}
}
}
This is similar to how Java OuterClass.this
is expressed in Kotlin as this@OuterClass
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With