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!

2
  • 6
    [email protected]() Commented Jul 30, 2018 at 9:52
  • @yole that's an answer ;) Commented Jul 30, 2018 at 10:07

1 Answer 1

13

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

Then in your case, you can call:

[email protected]() 

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 } } } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for your answer! So detailed!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.