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?
CodePudding user response:
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.
CodePudding user response:
It really depends on what you want to do with the lambda. If you do not need to access this
in order to access any private members of the class, you could define the lambda as a receiver function which is then called with the newly created object in the constructor or init
block like this:
data class Parent(
val lambda: Parent.() -> Unit
) {
init {
this.lambda()
}
}
Then you can use this
in the lambda that is a parameter of the constructor like this:
fun main() {
val list = mutableListOf<Parent>()
val parent = Parent { list.add(this) } // parent has been added to list on creation
}
However, as mentioned above, you cannot use this to break up the encapsulation of the class, e.g. if there is a private member x
defined inside Parent
, you cannot call this.x
, but only publicly accessible members.
CodePudding user response:
make the constructor method private and create a static factory method then you can create the parent and the chield objects and then inject the reference. After that, you can access them as you wish.