Store lambda in a variable in Kotlin
I am starting to develop in android with kotlin and I have a problem with lambdas. I have a function to set a listener in my view, it looks like this:
fun setListener(listener: () -> Unit) {
}
The problem is that the code passed as lambda will not be executed in the setListener function, it will be executed in another part of my code (in particular when the spinner item is selected), so I need to "store" or "store" this lambda into a variable / property so I can execute it when needed. Any idea on how to do this?
Edit: I achieved this:
private var listener: (() -> Unit)? = null
fun setListener(listener: () -> Unit) {
this.listener = listener
}
Is there a better way to do this? Thanks to
source to share
Here's how you can do it:
class Foo {
private var listener: () -> Unit = {}
fun setListener(listener: () -> Unit) {
this.listener = listener
}
}
However, it is not recommended to create setters manually in Kotlin. Instead, you can just post your property:
class Foo {
var listener: () -> Unit = {}
}
For reference: docs on properties with lots of examples.
source to share
You can easily store the function in a property. The easiest way:
var listener: (() -> Unit)? = null
Using:
foo.listener = { println("called") }
If you only want your property to be configured, you can create one public property with an unusable receiver and one private property for internal use. Complete example:
class Example {
// for internal use
private var _listener: (() -> Unit)? = null
// public set-only
var listener: (() -> Unit)?
@Deprecated(message = "set-only", level = DeprecationLevel.ERROR)
get() = throw AssertionError() // unusable getter
set(value) { _listener = value } // write-through setter
fun somethingHappend() {
_listener?.invoke()
}
}
source to share