Kotlin Lambda with Multiple Lines

Kotlin Lambda with Multiple Lines

In Kotlin, lambda function can span multiple lines, allowing you to write more complex logic within the lambda body.

The syntax for a lambda expression with multiple lines involves enclosing the body with curly braces {} and specifying the parameters before the arrow ->.

Let us go through an example.

In the following program, we define a lambda function that takes two integer values, and returns their sum. We have assigned the lambda function to a variable named sum. The lambda function has three lines in the body.

Kotlin Program

// Lambda function with multiple lines
val sum: (Int, Int) -> Int = { x, y ->
    val result = x + y                              //first line
    println("Calculating sum: $x + $y = $result")   //second line
    result                                          //third line
}

fun main() {
    val result = sum(3, 4)
    println("Sum: $result")
}

In the lambda function body,

  1. The first line val result = x + y adds the given integer values and stores the result in a variable.
  2. The second line is a println() statement.
  3. The third and last line is an expression result, which is considered as a return value. The last expression inside the lambda function is implicitly considered as a return value.

Output

Calculating sum: 3 + 4 = 7
Sum: 7