How to declare a function as a variable in Kotlin
So I am trying to create a listener in Kotlin. I just want to pass the method to be executed last in my code. Like this:
override fun setButtonClickListener(listener: (text: String) -> Unit) {
this.listener = listener
}
But, when I declare my listener, I have to declare it like this:
private var listener : (text: String) -> Unit = null!!
Otherwise my AS will complain. But this!! in empty object seams so weird. How should I declare this listener ??
Thank!
source to share
there are many ways to declare a function as a variable in kotlin.
you can use lateinit properties to initialize the property later, for example:
private lateinit var listener : (text: String) -> Unit
OR make the value listener
valid, but you must call it safe-call : listener?.handle(...)
like this:
private var listener : ((text: String) -> Unit)? = null
OR declare it an empty lambda to avoid an NPEx exception, e.g .:
private var listener : (String) -> Unit = {}
OR declare a private function and then you can refer to it by a function reference expression like:
private var listener = this::handle
private fun handle(text:String) = TODO()
Note: when declaring a function variable, the parameter name is optional, for example:
private var listener : (text:String) -> Unit = TODO()
// |--- parameter name is omitted
private var listener : (String) -> Unit = TODO()
source to share