Sobes.tech
Middle

How do lambda expressions work in Kotlin?

sobes.tech AI

Answer from AI

Lambda expressions in Kotlin are anonymous functions. They can be passed as arguments or stored in variables.

Key points:

  • Syntax: Curly braces {}. Parameters are specified before the arrow ->, and the function body after. If there are no parameters, the arrow is optional.
  • Implicit it parameter name: If a lambda has one parameter, it can be omitted, and it will be accessible under the name it.
  • Return value: The last expression in the lambda body is its return value.
  • Closures: Lambdas can access and modify variables from the scope in which they were defined.

Examples:

// Lambda without parameters
val hello = { println("Hello, world!") }
hello() // Call the lambda

// Lambda with one parameter (explicit declaration)
val square = { number: Int -> number * number }
println(square(5))

// Lambda with one parameter (using 'it')
val increment = { it + 1 }
println(increment(10))

// Lambda with multiple parameters
val sum = { a: Int, b: Int -> a + b }
println(sum(2, 3))

// Lambda as an argument to a higher-order function
fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}
println(operate(4, 5, { x, y -> x * y })) // Passing a lambda

Comparison with anonymous functions (more details):

Feature Lambda expression Anonymous function
Syntax {} fun (...)
Return value Last expression Explicit return
return inside Returns from the enclosing function (non-local return) Returns from the anonymous function itself (local return)
Usage of it Yes (for one parameter) No

Lambdas are widely used in Kotlin, especially with higher-order functions (map, filter, forEach, etc.), to create concise and expressive code. The compiler optimizes their usage.

How do lambda expressions work in Kotlin? — Kotlin - sobes.tech