Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 a method that will be executed latter in my code. Like this:

override fun setButtonClickListener(listener: (text: String) -> Unit) {
    this.listener = listener
}

But, when I declare my listener, I must declare it like this:

private var listener : (text: String) -> Unit = null!!

Otherwise my AS will complain. But this !! in a null object seams so weird. How should I declare this listener??

Thanks!

like image 497
Leandro Borges Ferreira Avatar asked Jul 07 '17 14:07

Leandro Borges Ferreira


1 Answers

there many ways to declare a function as a variable in kotlin.

you can using lateinit properties to initializing the property in later, for example:

private lateinit var listener : (text: String) -> Unit

OR make the listener nullable, but you must call it with safe-call: listener?.handle(...) in this way:

private var listener : ((text: String) -> Unit)? = null

OR declare it with a empty lambda to avoiding NPException, for example:

private var listener : (String) -> Unit = {}

OR declare a private function, and then you can reference it by function reference expression, for example:

private var listener = this::handle

private fun handle(text:String) = TODO()

Note: when you declare 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()
like image 70
holi-java Avatar answered Oct 03 '22 00:10

holi-java