Skip to content

Higher order functions

Devrath edited this page Feb 1, 2024 · 15 revisions

Definition

  • Higher-order functions are the ones that take functions as parameters or return function as a result.
  • We can even store the higher-order function in a variable and a data structure.
  • They enable functional programming concepts and allow you to write more concise and expressive code.

What are literals in kotlin

What is kotlin literals

Kotlin literal means a constant value assigned to a variable

val x = 10 // Integer literal
val y = 13.8 // Double literal
val z = "Hello" // String literal
#### `What is function literals`
* When we assign a function to a variable, It becomes a function literal
* There are 2 types of function literal
  * Lamda Expression
  * Anonymous Expression


## `Passing function as parameter`
**Define a caller in view**
```kotlin
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)
}

Returning Function

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