Store lambda in a variable in kotlin

android, kotlin, lambda

Solution

Here's how you can do it:

class Foo {
    private var listener: () -> Unit = {}
    fun setListener(listener: () -> Unit) {
        this.listener = listener
    }
}

However, manually writing setters is discouraged in Kotlin. Instead, you can just make your property public:

class Foo {
    var listener: () -> Unit = {}
}

For reference, here are the docs about properties with lots of examples.

Problem

I'm starting developing in Android with kotlin and I have a problem with lambdas. I have a function to set a listener in my view, this looks like this: ``` fun setListener(listener: () -> Unit) { } ``` The problem is that the code passed as lambda won't be executed in setListener function, it will be executed in another part of my code (specifically when an item of a spinner is selected) so I have to "save" or "store" this lambda into a variable/property so that I'm able to execute it when needed. Any idea about how to do it? Edit: I've achieved it by doing: ``` private var listener: (() -> Unit)? = null fun setListener(listener: () -> Unit) { this.listener = listener } ``` Is there a better way to do it? Thanks

Original source