Higher order function or higher level function can have another function as a parameter or return a function or can do both. Till now we have seen how we pass integer, string etc. as parameters to a function but in this guide, we will learn how we pass a function to another function. We will also see how a function returns another function.
Kotlin Higher order function example: Passing a function to another function
In the following example we are passing a function demo()
to another function func()
. To pass a function as a parameter to other function we use ::
operator before function as shown in the following example.
fun main(args: Array<String>) { func("BeginnersBook", ::demo) } fun func(str: String, myfunc: (String) -> Unit) { print("Welcome to Kotlin tutorial at ") myfunc(str) } fun demo(str: String) { println(str) }
Output:
Kotlin Higher order function example: function returns another function
In the following example the custom function func
is returning another function.
To understand this code, lets look at the function func
first, it accepts an integer parameter num
and in the return area we have defined a function (Int) -> Int = {num2 -> num2 + num}
so this is the other function which also accepts integer parameter and returns the sum of this parameter and num
.
You may be wondering why we have passed the value 20 as a parameter in sum
, well this is because the function func
returned the function so the sum
is the function that will accept the int parameter. This is the same function that we have defined in the return area of function func
.
fun main(args: Array<String>) { val sum = func(10) println("10 + 20: ${sum(20)}") } fun func(num: Int): (Int) -> Int = {num2 -> num2 + num}
Output:
Leave a Reply