Skip to content

Passing function as parameter

Devrath edited this page Feb 10, 2024 · 4 revisions

Define a caller in view

AppButton(text = "Passing Functions as parameter", onClick = {
            // Here will will calculate the square of a number
            val input = 5
            // Call the functionality
            val result = viewModel.performOperation(input) { input ->
                input * input
            }
            println(result)
})

Define the calling function in the view model

fun performOperation(input: Int, operation: (Int) -> Int): Int {
        return operation(input)
}
Clone this wiki locally