Pass lambda to higher-order functions (Kotlin)

Aman Srivastava
2 min readJul 22, 2021

--

In the previous articles, we have talked about the Lambda Expression, its definition, how to assign it to a variable, types of such variables, its execution, and passing parameters to the lambda expression.

In this article, we are going to discuss how to pass a lambda expression to a function.

A function that uses a lambda expression as a parameter is known as a higher-order function.

e.g. doubleIt(25, {i : Int -> i * 2})

fun doubleIt(x: Int, twice: (Int) -> Int) : Int {
var result = twice(x)
print(“Value of $x is doubled to $result)

return result

}

In the above example, the higher-order function will double the value and will take two arguments — an Int and a lambda expression which shall process the value. We pass the Int variable to lambda expression so as to double its value. ‘25’, here, is the parameter value, and “{i: Int -> i * 2}” is the lambda expression.

If the higher-order function is taking only a single parameter along with the lambda expression then, you may take the lambda expression out of the parenthesis.

e.g. doubleIt(25) {i : Int -> i * 2}

If the function is taking only the lambda expression then, you may remove the parenthesis altogether.

e.g. display {print(“Hello World”)}

If your lambda expression has only one parameter, you can replace it with “it”. Further, you can not only pass lambda as a parameter but also can return a lambda. e.g.

fun getValue(value : Int) : (Int) -> Int {

if (value > 10) {
return { it * value}
else if (value < 10 && value > 5) {
return {it / value}
else {
return { it }
}

You can assign a return value of the lambda expression to a variable.

e.g. val result = getValue(8) (2)

It is also possible that you receive lambda expression(s) and return a lambda expression in the same function.

Let’s look at a function that takes two lambda expressions, combines them, and returns the combined lambda expression:

fun combine(lambda1 : (Int) -> Int, lambda2: (Int) -> Int) : (Int) -> Int {

return { x: Int -> lambda1(lambda2(x)) }
}

An example of this would be,

val kgsToPounds = { x: Double -> x * 2.204623 }
val poundsToUSTons = { x: Double -> x / 2000.0 }
val kgsToUSTons = combine(kgsToPounds, poundsToUSTons)

In a more concise manner, you can define a type alias which is not limited to only the function type but to any type.

e.g. typealias IntConversion = (Int) -> Int

The above example can be rewritten as,

fun combine(lambda1 : IntConversion, lambda2: IntConversion) : IntConversion {

return { x: Int -> lambda1(lambda2(x)) }

}

Similarly, you can define alias of other types

typealias EmployeeArray = Array<Employee>

--

--