Wednesday, August 15, 2018

Kotlin - Higher order functions

In Kotlin, functions can be represented as values by using lambdas or function references.  Regular functions receive only data parameters, whereas a function that receives another function as a parameter and returns a function as a result is called a Higher-order function.

Therefore, a higher-order function is any function to which you can pass a lambda or a function reference as an argument, or a function which returns one, or both.

Kotlin allows us to define a function which takes a function (a literal) as a parameter. The syntax for this looks like the following.
Example - 1
fun function(function: (String) -> String){ }
Here, you  can see an example of a higher-order function that takes a function as an argument:
Example - 2
fun calculate(x: Int, y: Int, operation: (Int, Int) -> Int): Int { return operation(x, y) } fun sum(x: Int, y: Int) = x + y fun main(args: Array<String>) { val result = calculate(4, 5, ::sum) println(result) } Output- 9

  • As you can see above, we have declared a higher-order function that takes two parameters x and y. In addition it takes another function as a parameter, named operation that itself takes two parameters of type integer and returns an integer.
  • Invoke the function passing in the arguments supplied.
  • Declare a function that matches the same signature.
  • Invoke the higher-order function passing in as the function argument, ::sum which is how we reference a function by name in Kotlin.

Here is an example of a higher order function that returns a function.
Example - 3
fun operation(): (Int) -> Int { return ::square } fun square(x: Int) = x * x fun main(args: Array<String>) { val func = operation() println(func(2)) } Output- 4

  • Declare a higher-order function that returns a function.
  • Return a function matching the signature.
  • Invoke operation to get the result assigned to a variable.
  • Invoke the function.

Kotlin stdlib includes also different extension higher order functions like let, run, apply, also, takeIf and takeUnless. Similarly, like collection processing functions, they are often used all around the projects.

Kotlin features are included to support higher order functions.

  • Inline functions (higher-order improve efficiency of higher order functions) implicit name of the single parameter (rarely useful for defining functions as a value because type inference is not possible, but extremely useful in lambdas provided as arguments)
  • Last lambda in the argument convention (another way to support passing functions as an argument)
  • Fact that such an important features exist to support higher order functions clearly shows how important they are. 


Get it on Google Play

Android - Scoped storage OS 11

Every Android updated version has something for developers and users alike. The Android 10 version has many user-friendly and performance en...