9

My question is almost like this question Java: calling outer class method in anonymous inner class . But this time we are in Kotlin.

As the example below, I want to call funB() in the object expression, but I only made two failures.

class A {
    lateinit var funA: () -> Unit
    lateinit var funB: () -> Unit

    fun funC()  {
        var b = object : B() {
            override fun funB() {
                funA() // A.funA()

                // Two attempts to fail
                funB() // b.funB(), not my expect
                A::funB() // compile error
            }
        }
    }
}

Thank you for your answer!

Bear Big
  • 93
  • 7

1 Answers1

13

You can qualify this with a @ to obtain an equivalent of java: MyClass.this ->this@MyClass

Then in your case, you can call:

this@A.funB()

From the doc:

To access this from an outer scope (a class, or extension function, or labeled function literal with receiver) we write this@label where @label is a label on the scope this is meant to be from:

class A { // implicit label @A
    inner class B { // implicit label @B
        fun Int.foo() { // implicit label @foo
            val a = this@A // A's this
            val b = this@B // B's this

            val c = this // foo()'s receiver, an Int
            val c1 = this@foo // foo()'s receiver, an Int

            val funLit = lambda@ fun String.() {
                val d = this // funLit's receiver
            }


            val funLit2 = { s: String ->
                // foo()'s receiver, since enclosing lambda expression
                // doesn't have any receiver
                val d1 = this
            }
        }
    }
}
crgarridos
  • 8,758
  • 3
  • 49
  • 61