DEV Community

Discussion on: Can someone explain this Kotlin expression.

Collapse
 
vishnuharidas profile image
Vishnu Haridas
protected var callbackFunction: ((Boolean) -> Unit) = {}

This variable is of type "function". In Kotlin, functions are first-class citizens, that means, you can use functions just like other variables --- pass functions as parameters to other functions, store functions in variables etc.

You can read that expression like this: "The variable callbackFunction is of type Function --- that accepts a Boolean and returns a Unit."

Later you can assign a function to the variable like this:

callbackFunction = { b: Boolean ->
    println("The value is a $b")
}

...or this:

fun showResults(b: Boolean){
    println("The value is $b")
}

callbackFunction = ::showResults   // assign by reference

Also, the variable is initialized by assigning an anonymous function like {}.

Collapse
 
abhinav1217 profile image
Abhinav Kulshreshtha

Special thanks for assign by reference example. It is a nice trick which I should use in future codes.