0
0
KotlinConceptBeginner · 3 min read

What is Trailing Lambda in Kotlin: Simple Explanation and Example

In Kotlin, a 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.

kotlin
fun greet(name: String, action: () -> Unit) {
    println("Hello, $name!")
    action()
}

fun main() {
    greet("Alice") {
        println("Welcome to Kotlin!")
    }
}
Output
Hello, Alice! 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.
âś…

Key Takeaways

Trailing lambda lets you place the last lambda argument outside parentheses for cleaner code.
It improves readability especially for long or multi-line lambda expressions.
Use trailing lambdas in functions that take code blocks like callbacks or builders.
This syntax is common and encouraged in Kotlin standard library functions.
Trailing lambdas are optional but help make your code more expressive and neat.