High order functions

A high order function is a function which accepts another function as a parameter or returns another function. We just saw how we can use a function as a property, so it's quite easy to see that we can accept another function as a parameter or that we can return another function from a function. As stated previously, technically the function that receives or returns another function (it may be more than one) or does both is called a high-order function.

In our first lambda example in Kotlin, the invokeSomeStuff function was a high-order function.

The following is another example of high-order function:

fun performOperationOnEven(number:Int,operation:(Int)->Int):Int { 
    if(number%2==0) { 
        return operation(number) 
    } else { 
        return number 
    } 
} 
fun main(args: Array<String>) { 
    println("Called with 4,(it*2): ${performOperationOnEven(4, 
            {it*2})}") 
    println("Called with 5,(it*2): ${performOperationOnEven(5, 
            {it*2})}") 
} 

In the preceding program, we created a high order function—performOperationOnEven which would take an Int and a lambda operation to execute on that Int. The only catch is that the function would only perform that operation on the provided Int, if that Int is an even number.

Isn't that easy enough? Let's have a look at the following output:

In all our previous examples, we saw how to pass a function (lambda) to another function. However, that's not the only feature of high order functions. A high order function also allows you to return a function from it.

So, let us explore it. Have a look at the following example:

fun getAnotherFunction(n:Int):(String)->Unit { 
    return { 
        println("n:$n it:$it") 
    } 
} 
fun main(args: Array<String>) { 
    getAnotherFunction(0)("abc") 
    getAnotherFunction(2)("def") 
    getAnotherFunction(3)("ghi") 
} 

In the preceding program, we created a function, getAnotherFunction, that would take an Int parameter and would return a function that takes a String value and returns Unit. That return function prints both its parameter (a String) and its parents parameter (an Int).

See the following output:

In Kotlin, technically you can have nested high order functions to any depth. However, that would do more harm than help, and would even destroy the readability. So, you should avoid them.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.188.121