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:

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:

The result:


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:

The output:


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:

The output of the above code:

The value is between 11 to 20