In Kotlin, a higher-order function is a function that takes one or more functions as arguments, or returns a function as its result. It enables you to treat functions as first-class citizens, meaning you can use them just like any other values, such as integers or strings.
Passing lambda expression as a parameter to Higher-Order Function –
Two types of lambda you can passed
- Lambda which returns Unit type
- Lambda which return any value like String,Integer etc.
1. lambda expression returns nothing
var lambda = {
println("\nHello world")
}
fun highOrderFun( lmbd : () ->Unit){
// lmbd()
lmbd.invoke() // also calling function using invoke
}
fun main() {
highOrderFun(lambda) // Hello world
}
2. lambda expression which returns Integer value
val lambda2 = { x:Int, y:Int -> x * y }
fun highOrderFun2(lmbd :(Int, Int) -> Int){
val r = lmbd.invoke(10,3)
print(r)
}
fun main() {
highOrderFun2 (lambda2) // 30
}
Passing function as a parameter to Higher-Order function :
// function which returns nothing
fun f1(s:String):Unit{
print(s)
}
// function which returns nothing
fun f2(i1:Int, i2:Int):Int{
return i1+i2
}
fun main() {
higherOrderFun3(12,2, "Hello world", ::f1,::f2)// passing f1 f2 function reference
val square = higherOrderFun4()
print("\n" + square(12,10)) // 93
}
// passing function
fun higherOrderFun3(x:Int,y:Int,str:String, l1:(String) ->Unit, l2 :(Int,Int) ->Int){
val r= l2.invoke(x, y)
print("\n $r")
l1.invoke("\n $str") // Hello world
}
// return another function from higher order function
fun higherOrderFun4(): ((Int, Int) -> Int){
return ::f2
}
Output:
14
Hello world
22