How to get a class instance inside a lambda expression in Kotlin?

Viewed 495

In java when I want to get the outer class instance from an Inner class I'm writing OutClass.this. In Kotlin, inside a lambda expression is there a way to get an instance of the class where the lambda expression is written if the lambda is running with a receiver? Lets say we have the following code:

class Dog
{
    fun funcA () : Unit
    {
        println("Dog funcA")
    }
}  
class OuterClass
{ 
   var d : Dog = Dog()
   fun funcA () : Unit
   {
        println("OuterClass funcA")
   }
   
  fun funcWithLambda() : Unit
  {
      d.apply(){
         //place where I want to call OutClass method *funcA*
         // writing *this* will refer to *Dog* instance
         }
  }
}
2 Answers

You're looking for this@OuterClass.funcA().

I'm allergic to labels, so much prefer to assign to explicitly named variables:

val outer: OuterClass = this
d.apply() {
    val inner: Dog = this
    outer.funcA()
    inner.funcA()
}

Even better is to avoid different this contexts entirely (obviously your example is contrived, so so is this one):

fun funcWithoutLambda(): Unit {
    funcA()
    d.funcA()
}
Related