Search code examples
kotlinlambdathis

Is it possible to access parent object from within its lambda property?


I need to access the instance of a class from inside the function stored in its constructor property, like this

data class Parent(
    val lambda: () -> Unit = {
        // I need the instance of the enclosing Parent here
        // this@Parent doesn't work
    }
)

Is this possible?


Solution

  • No, this isn't possible because the Parent object doesn't exist at the point when the lambda is created. The lambda is being passed as an argument to the constructor that will create the object, so the lambda has to be created first.

    If the lambda was created inside the class instead of being passed to the constructor, you would be able to use this to access the containing object.