How to Create Lambda in Kotlin: Simple Syntax and Examples
In Kotlin, you create a lambda using the syntax
{ parameters -> body }. Lambdas are anonymous functions that can be stored in variables or passed as arguments to other functions.Syntax
A lambda expression in Kotlin is written inside curly braces { }. It can have parameters followed by an arrow -> and then the function body. If there are no parameters, you can omit the arrow.
- Parameters: Variables passed to the lambda.
- Arrow (->): Separates parameters from the body.
- Body: The code executed when the lambda is called.
kotlin
val sum: (Int, Int) -> Int = { a, b -> a + b }Example
This example shows how to create a lambda that adds two numbers and how to call it.
kotlin
fun main() {
val add: (Int, Int) -> Int = { x, y -> x + y }
val result = add(5, 3)
println("Sum is: $result")
}Output
Sum is: 8
Common Pitfalls
Common mistakes include forgetting the arrow -> between parameters and body, or mismatching the lambda type with its usage.
Also, if a lambda has only one parameter, you can use it as an implicit name without declaring it.
kotlin
fun main() {
// Wrong: missing arrow
// val wrongLambda: (Int) -> Int = { x x * 2 }
// Correct:
val correctLambda: (Int) -> Int = { x -> x * 2 }
// Using implicit 'it' for single parameter
val implicitIt: (Int) -> Int = { it * 2 }
println(correctLambda(4)) // Output: 8
println(implicitIt(5)) // Output: 10
}Output
8
10
Key Takeaways
Use curly braces with parameters and arrow to create a lambda in Kotlin.
Lambdas can be stored in variables and passed as function arguments.
For single-parameter lambdas, use implicit 'it' to simplify code.
Always match the lambda type with its expected function signature.
Remember the arrow '->' separates parameters from the lambda body.