As we all know that in Kotlin, we can pass a function as a parameter in the function. In Kotlin, we are using high order functions in order to implement the business logic and get the result.
Syntex:-
1 2 3 4 5 6 7 8 9 |
var lambda = {println("Hello, this is my function.") } // higher-order function fun higherfunc( lmbd: () -> Unit ) { // accepting lambda as parameter lmbd() //invokes lambda expression } fun main(args: Array<String>) { //invoke higher-order function higherfunc(lambda) // passing lambda as parameter } |
In kotlin, we can combine two methods and get the result as Lambdas are a further level of abstraction which give you the opportunity to make behavior variables, you still have to provide them with data. We can Achieve it using the Extention function.
Let see the composition of two methods in Kotlin:-
1 2 3 4 5 6 7 8 9 10 11 12 |
// Extension function on lambda private infix fun ((Int, Int) -> Int).plus(f: (Int, Int) -> Int) = { p1: Int, p2: Int, p3: Int, p4: Int -> this(p1, p2) + f(p3, p4) } // Usage val func1: (Int, Int) -> Int = { a, b -> a + b } val func2: (Int, Int) -> Int = { a, b -> a * b } // first two parameters (1 and 2) for the `first` lambda, // second two parameters (4 and 3) for the `second` lambda val sum = (first plus second)(1, 2, 4, 3) // result is 15 |
We can see the output on the console:-
In order to get more details, You can go through the following link:-
https://kotlinlang.org/docs/reference/extensions.html
https://kotlinlang.org/docs/reference/lambdas.html