hsz
hsz

Reputation: 152216

Access class context in lambda function passed in constructor

I have created a class that takes an input parameter which is a lambda function:

class MyClass(var onClick: () -> Unit) {
    private val title = SomeComponent()

    init {
        // register some listeners that finally invokes `onClick`
        // for simplicity, let's assume:

        title.addKeyListener(object : KeyListener {
            override fun keyPressed(e: KeyEvent?) {
                onClick()
            }
        })
    }
}

This MyClass is initialized with the onClick provided:

val instance = MyClass(
    onClick = {
        // some logic
    }
)

Is it possible to access the class context from inside the onClick function?

Upvotes: 1

Views: 646

Answers (1)

Willi Mentzel
Willi Mentzel

Reputation: 29844

Sure, you could give onClick MyClass as receiver.

class MyClass(var onClick: MyClass.() -> Unit) { //...

    init {
        //...
        onClick()
        //...
    }
}

fun main() {
    MyClass { 
        // "this" is the instance of MyClass here
    }
}

In the init block you have three options to invoke onClick():

this.onClick()
onClick(this)
onClick() // is invoked on this, but this is omitted

I would go with the last one.

Upvotes: 3

Related Questions