Let's quickly refresh how to work with function variables. We can define a variable with a functional type like this:
var onClickHandler: (ViewState) -> Unit = {}
We can then reassign that stored function as with any other variable:
fun main() {
onClickHandler = { viewState ->
println("viewState -> ${viewState.title}
${viewState.subtitle}")
}
}
And finally, since the variable represents a function, we can invoke the function in several different ways by referencing the variable name, as follows:
fun main() {
onClickHandler = { viewState ->
println("viewState -> ${viewState.title}
${viewState.subtitle}")
}
val viewState = ViewState("Hello", "Kotlin")
onClickHandler(viewState)
onClickHandler.invoke(viewState)
}
By allowing us to store and update variables with a functional type, Kotlin enables us to start thinking in terms of functions and writing code that more heavily relies on functional operations.