What is Trailing Lambda in Kotlin: Simple Explanation and Example
trailing lambda is a syntax feature that lets you pass a lambda expression outside the parentheses of a function call if the lambda is the last argument. This makes the code cleaner and easier to read, especially when the lambda is long or complex.How It Works
Imagine you are ordering food and you want to add special instructions. Instead of writing all instructions inside the main order form, you write them on a separate note attached to the order. In Kotlin, a trailing lambda works similarly: if the last argument of a function is a lambda (a block of code), you can write it outside the parentheses for clarity.
This helps keep your code neat and readable. Instead of crowding the function call with a big block of code inside parentheses, you place the lambda after the call, making it look like a natural extension of the function.
Example
This example shows a function that takes a lambda as its last argument. We call it using trailing lambda syntax for better readability.
fun greet(name: String, action: () -> Unit) {
println("Hello, $name!")
action()
}
fun main() {
greet("Alice") {
println("Welcome to Kotlin!")
}
}When to Use
Use trailing lambdas when your function’s last argument is a lambda expression. This is common in Kotlin for functions that take blocks of code, like callbacks, builders, or collection operations.
Trailing lambdas make your code easier to read and write, especially when the lambda is long or multi-line. For example, when working with UI event handlers or configuring objects, trailing lambdas keep your code clean and expressive.
Key Points
- Trailing lambda syntax lets you write the lambda outside the parentheses if it is the last argument.
- This improves readability by separating the main function call from the lambda block.
- It is widely used in Kotlin standard library functions like
apply,run, and collection operations. - Trailing lambdas are optional but recommended for cleaner code style.