What is Kotlin lambda?

In Kotlin, you may define and use the lambda and anonymous function, that is called “function literals”.

The ‘function literal’ is the function that is not declared and passed immediately as an expression.

How to define lambda function?

The lambda expression is always surrounded by curly braces as shown below:

val name : Type = { arguments -> code }

You may also write lambda function like this:

val sum = { x: Int, y: Int -> x + y }

A few things to note:

  • You may declare the parameters in full syntactic form inside the curly braces.
  • The parameters can optionally have type annotations.
  • The body of the function is given after the –> sign.
  • Return value of the function is the last expression inside the lambda body if the return type of the lambda is not Unit.

Now, let us look at a few examples of using the Kotlin lambda functions.

Simply displaying a message using a lambda function

We will simply display a message using the lambda function:

fun main(args: Array<String>) {



    val msg = { println("Kotlin Lambda Tutorial!")}

    msg()

}

The output:

Kotlin Lambda Tutorial!

An example of lambda function with parameters

In this example, we will get the sum of two parameters in the lambda function. The sum is displayed as follows:

fun main(args: Array<String>) {



    val sum = { a: Int, b: Int -> a + b }



    println(sum(10,20))

}

The result:

30

Leaving the optional annotations example

The same can be achieved as in the above example without using the optional annotations. So, the code looks like this:

fun main(args: Array<String>) {



    val sum: (Int, Int) -> Int = { a, b -> a + b }



    println(sum(50,50))

}

The output:

100

The example of the lambda return value

As mentioned in the introductory part, the return value of the lambda is the last expression if the return type is not Unit.

The example below uses when expression to demonstrate that:

fun main(args: Array<String>) {



    val retDemo = { grade : Int ->

        when(grade) {

            in 1..10 -> "The value is between 1 to 10"

            in 11..20 -> "The value is between 11 to 20"

            in 21..30 -> "Between 21 to 30"

            in 31..40 -> "Between 31 to 40"

            else -> "Above 40"

        }

    }

    print(retDemo(19))

}

The output of the above code:

The value is between 11 to 20

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!