Lambda Syntax
In this page:
Writing a Basic Lambda
A lambda is written inside curly braces, with parameters (if any) listed before an arrow ->, followed by the body. The last expression in the body becomes the lambda's result.
Example: Writing a Basic Lambda
fun main() {
val square = { x: Int -> x * x }
println("Square of 5: ${square(5)}")
}
Login to try C/C++/Java/PHP code in the editor
Lambdas with No Parameters
When a lambda takes no parameters, the arrow and parameter list are simply omitted, leaving just the body inside the braces.
Example: Lambdas with No Parameters
fun main() {
val sayHello = { println("Hello from a lambda!") }
sayHello()
}
Login to try C/C++/Java/PHP code in the editor
Lambdas with Multiple Parameters
A lambda can take several parameters, separated by commas before the arrow, just like a regular function's parameter list.
Example: Lambdas with Multiple Parameters
fun main() {
val add = { a: Int, b: Int -> a + b }
println("Sum: ${add(3, 4)}")
}
Login to try C/C++/Java/PHP code in the editor
Passing a Lambda to a Function
Lambdas are often written directly at the call site of a function that expects one, such as with collection operations, rather than being stored in a variable first.
Example: Passing a Lambda to a Function
fun main() {
val numbers = listOf(1, 2, 3, 4)
val doubled = numbers.map { n -> n * 2 }
println(doubled)
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the arrow
->that separates a lambda's parameters from its body when parameters are explicitly named. - Adding unnecessary parentheses around a lambda's parameter list; lambda parameters are not wrapped in
()like a regular function's are. - Trying to write
returninside a lambda assigned to a variable and expecting it to just exit the lambda, when it actually performs a non-local return if the lambda is inlined.
- A lambda expression is written as
{ parameters -> body }, and can be assigned to a variable or passed directly to a function. - If a lambda has no parameters, the
->and everything before it is omitted entirely. - The last expression inside a lambda's body is automatically its return value.
- Lambdas can be stored in variables with a function type, such as
val add: (Int, Int) -> Int.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: