How to Pass Lambda to Function in Kotlin: Simple Guide
In Kotlin, you pass a lambda to a function by declaring a parameter with a function type like
(Int) -> Int and then calling the function with a lambda expression. You can place the lambda outside the parentheses if it is the last argument for cleaner syntax.Syntax
To pass a lambda to a function, declare a parameter with a function type specifying input and output types. Call the function by passing a lambda expression matching that type.
- Parameter:
operation: (Int) -> Intmeans a function taking anIntand returning anInt. - Calling: Pass a lambda like
{ x -> x * 2 }matching the parameter type. - Trailing lambda: If the lambda is the last argument, you can put it outside the parentheses.
kotlin
fun applyOperation(x: Int, operation: (Int) -> Int): Int {
return operation(x)
}
// Calling with lambda inside parentheses
val result1 = applyOperation(5, { x -> x * 2 })
// Calling with trailing lambda outside parentheses
val result2 = applyOperation(5) { x -> x * 2 }Example
This example shows a function that takes a lambda to double a number. It demonstrates both ways to pass the lambda: inside parentheses and as a trailing lambda.
kotlin
fun applyOperation(x: Int, operation: (Int) -> Int): Int {
return operation(x)
}
fun main() {
val result1 = applyOperation(10, { num -> num * 2 })
println("Result1: $result1")
val result2 = applyOperation(10) { num -> num * 2 }
println("Result2: $result2")
}Output
Result1: 20
Result2: 20
Common Pitfalls
Common mistakes include:
- Not matching the lambda parameter types with the function parameter type.
- Forgetting to use the trailing lambda syntax correctly.
- Trying to pass a lambda without specifying the function type in the parameter.
Here is an example of a wrong and right way:
kotlin
fun wrongExample(x: Int, operation: Int) {
// This is wrong because operation is not a function type
}
fun rightExample(x: Int, operation: (Int) -> Int) {
println(operation(x))
}
fun main() {
// Wrong: won't compile
// wrongExample(5, { it * 2 })
// Right:
rightExample(5) { it * 2 }
}Output
10
Quick Reference
Remember these tips when passing lambdas to functions in Kotlin:
- Declare the parameter with a function type like
(Type) -> ReturnType. - Pass the lambda inside parentheses or as a trailing lambda if it is last.
- Use
itas an implicit name for single lambda parameters. - Ensure the lambda matches the expected parameter and return types.
Key Takeaways
Declare function parameters with function types to accept lambdas.
Pass lambdas inside parentheses or as trailing lambdas for cleaner code.
Use 'it' for single-parameter lambdas to simplify syntax.
Always match lambda parameter and return types with the function signature.
Avoid passing non-function types where lambdas are expected.