Kotlin Lambda Expression Tutorial

In this section, we will learn what the lambda expression is and how to use it in Kotlin.

What is Lambda Expression in Kotlin?

Lambda is a function but without a name (AKA anonymous function)! You can pass a lambda to a variable, a parameter or even make a function to return a lambda as a result!

Basically, using lambda, we can create a block of code which is able to be passed around and gets executed in different places!

How to Create a Lambda Expression in Kotlin? Kotlin Lambda Expression Syntax:

This is the syntax of a lambda expression:

{

    param1:data-type, param_n:data-type →

/*

The body of the lambda expression where we can put one or more instructions

*/

}

{}: the pair of curly braces define the boundary of a lambda expression.

param1, param_n: these are the parameters of the lambda expression that we’re building. Creating parameters for a lambda expression is the same as the way we create parameters for typical function, with the exception that we create parameters of lambda expressions within the boundary of the curly braces of that lambda.

: the arrow symbol that comes after the parameters of a lambda expression separates the parameters section from the body section of a lambda expression. Basically, after symbol, you have the body of the expression where you can write one or more instructions to be executed when there was a call for the lambda.

Notes:

  • If the lambda expression does not have any parameter, then we can remove the symbol and directly write instructions of the lambda after the opening curly braces as:
{

// write the instructions of the lambda here…

}
  • The last expression of a lambda is considered as its return value.

Now, as mentioned before, we can, for example, pass a lambda as the value for a variable and use that variable to invoke the body of the lambda in later time.

For example:

var variableName = {
    param1:Int, param2:Int →
    param1 + param2
}
variableName(10,20)

Example: creating a lambda expression in Kotlin

fun main(){

    var multiply = {
        num1:Int ,num2: Int -> 
        num1 * num2 
    }
    
    println(multiply(400, 3))
}

Output:

1200

Kotlin Lambda Type (AKA Function Type)

The Lambda expression has a type! For example, when you want to set the parameter for a function that takes a lambda expression, you need to set its type, otherwise you’ll get error. Or if you want to return a lambda as the return type of a function, again you need to set its type in the signature of the function first!

This is how we declare the data type of a lambda:

(param1-data-type, param2-data-type) → return-data-type

For example:

(Int,Int)→ String

This data type refers to a lambda expression where it has two parameters and both are of type Int and also it returns a value (the last expression of the lambda) which is of type String. So if you set this data-type for a parameter, for example, then it’s your responsibility to pass a lambda with this signature.

Note that if a target lambda expression does not have any parameter, then you need to put an empty pair of parentheses like:

() → data-type

Invoking a Lambda in Kotlin

In order to invoke a lambda expression, we can call the parameter or variable that holds a reference to the lambda, and pass the required argument to the variable as if it was a function.

Or we can call the invoke() function on top of the target variable and then pass the arguments.

lambdaVariableName(arg1,arg2)

lambdaVariableName.invoke(arg1,arg2)

Both methods above, work perfectly fine.

Note that in the examples above, the perception is that the target lambda expression has two parameters! That’s why we’ve passed two arguments. But if there wasn’t any parameter, then simply call the pair of parentheses without any argument being passed to the lambda expression.

Kotlin Higher Order Function:

As mentioned before, we can pass a lambda expression as the argument to a function. Such a function is called higher order function.

For this to happen, the target parameter’s data type must be set to the type of a lambda expression and we can pass a lambda expression as the argument to that parameter.

Example: creating functions with parameters of function type

fun main(){

    multiply({num1:Int ,num2: Int ->num1 * num2})
}

fun multiply(lam:(Int,Int)->Int){
    println(lam.invoke(10,20))
}

Output:

200

Kotlin Function Return Value of Lambda Type:

We can return a lambda expression from a function as a result of calling it as well!

For this to happen, we need to set the return data type of that function to the type of a lambda expression.

Example: creating functions with return value of function type

fun main(){

    var res = returnLambda()

    println(res(3,5))
}

fun returnLambda():(Int,Int)->Int{
    return {
        x:Int, y:Int-> x *y 
    }
}

Output:

15

Kotlin Lambda and the it Keyword

When you have a variable or parameter that already defined the data-type of the lambda expression that it can accept, if the target lambda had only one parameter, we can remove the declaration of that single parameter and refer to the parameter using the keyword it in the body of the lambda. This is because the Kotlin compiler can now infer the data type of that single parameter using the data type we’ve set for the related variable or parameter.

Example: using the it keyword in Kotlin lambda

fun main(){

    var printName: (String)->Unit = {println("The name is: $it")}

    printName("Jack")

}

Output:

The name is: Jack

As you can see, the lambda expression in this example didn’t declare the parameter, but we could access the value of the parameter using the it keyword.

Kotlin functions with last parameter of type Lambda

If there’s a function with its last parameter set to a lambda type (AKA function type) then we can pass the argument for that last parameter outside the pair of parentheses that we use when calling a function!

Let’s run the example below to see how this works.

Example: calling functions with last parameter set to a lambda type

fun main(){

    printDetails("John"){println("The name is: $it")}
}

fun printDetails(name:String, print:(String)->Unit){
    print(name)
}

Output:

The name is: John

Here you can see that the value we’ve passed for the second parameter of the printDetials function is set outside of the parentheses.

Kotlin functions with one parameter of function type

If a function has only one parameter and that is of a function type, then at the time of calling the function, we can remove the parentheses entirely and directly set the lambda argument after the name of the function.

Let’s see the example below to see how this works.

Example: calling a function with one function type parameter

fun main(){

    var array = arrayOf(1,2,3,4,5,6)

    array.forEach {println("The element of the array is: $it")}

}

Output:

The element of the array is: 1

The element of the array is: 2

The element of the array is: 3

The element of the array is: 4

The element of the array is: 5

The element of the array is: 6

An object of type Array has a function called forEach() that has one parameter of function type (it takes one lambda expression only) and it calls that lambda for each element in the array.

So here we called the forEach function and passed it a lambda expression which as you can see there’re no parentheses used to surround the lambda expression.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies