Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call outer class' super method from inner class in Kotlin?

Tags:

kotlin

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...
    }
}
like image 577
Siegmeyer Avatar asked Jul 28 '17 12:07

Siegmeyer


People also ask

Can inner class calling Outer method?

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.

Can inner class access outer class methods?

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.

How do I call inner class Kotlin?

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.


1 Answers

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.

like image 85
hotkey Avatar answered Sep 21 '22 04:09

hotkey