Siegmeyer
Siegmeyer

Reputation: 4512

How to call outer class' super method from inner class in 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...
    }
}

Upvotes: 23

Views: 12190

Answers (3)

marko
marko

Reputation: 457

According to this section on inner classes, you can simply call outer method:

class Outer {

    inner class Inner {
        fun foo() { 
            bar() 
        }
    }

    private fun bar() {}
}

Upvotes: 6

hotkey
hotkey

Reputation: 147951

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.

Upvotes: 37

aygavras
aygavras

Reputation: 180

This would be the equivalent in Kotlin:

internal class Outer {
    internal inner class Inner {
        fun myMethod() {
            println([email protected]())
        }
    }

    override fun toString(): String {
        return "Blah"
    }
}

Upvotes: 1

Related Questions