Skip to content

Returning Function

Devrath edited this page Feb 10, 2024 · 2 revisions

Define a caller in view

AppButton(text = "Passing Functions as parameter", onClick = {
            // We pass a operation here
            val addFunction = viewModel.createCalculator("add")
            // We use the operation passed above to pass values for it
            val resultAdd = addFunction(5, 3) // Result is 8
            println("Result (Add): $resultAdd")
})

Define the calling function in the view model

fun createCalculator(operator: String): (Int, Int) -> Int {
        return when (operator) {
            "add" -> { a, b -> a + b }
            "subtract" -> { a, b -> a - b }
            "multiply" -> { a, b -> a * b }
            "divide" -> { a, b -> if (b != 0) a / b else 0 }
            else -> throw IllegalArgumentException("Unknown operator: $operator")
        }
}

Clone this wiki locally