The basic syntax follows:
'{' and '}' denote the lambda function.{ parameters -> body }
'->' separates the parameters from the body of lambda.
'body' is the code that gets executed when lambda is invoked.
Kotlin Lambda Function Examples
Expressing lambdas as expression:
Using Lambda Functionsval add: (Int, Int) -> Int = { a, b -> a + b } val sum = { a: Int, b: Int -> a + b } val printMessage: (String) -> Unit = { message -> println(message)} val multiply = { a, b -> a * b } // Compiler infers parameter types
val add: (Int, Int) -> Int = { a, b -> a + b } val result = add(3, 4) // result is now 7 // Inline usage without storing in variables val numbers = listOf(1, 2, 3, 4, 5) val squaredNumbers = numbers.map {number -> number * number } val sum = numbers.reduce { acc, num -> acc + num }