0
0
Kotlinprogramming~5 mins

Trailing lambda convention in Kotlin

Choose your learning style9 modes available
Introduction
The trailing lambda convention makes code easier to read and write when a function's last argument is a lambda (a block of code). It helps keep the code clean and clear.
When calling a function that takes a lambda as its last argument.
When you want to write cleaner and more readable code with lambda expressions.
When you want to pass a block of code outside the parentheses for better style.
When using Kotlin standard library functions like 'apply', 'let', or 'run'.
Syntax
Kotlin
fun functionName(param1: Type, lambdaParam: () -> Unit) {
    // function body
}

// Calling with trailing lambda:
functionName(param1) {
    // lambda code here
}
The lambda block is placed outside the parentheses if it is the last argument.
If the lambda is the only argument, you can omit the parentheses entirely.
Examples
Here, the lambda is passed outside the parentheses as the last argument.
Kotlin
fun greet(name: String, action: () -> Unit) {
    println("Hello, $name!")
    action()
}

greet("Alice") {
    println("Welcome!")
}
The 'forEach' function takes a lambda as its only argument, so parentheses are omitted.
Kotlin
listOf(1, 2, 3).forEach {
    println(it)
}
When the lambda is the only argument, you can call the function with just the lambda block.
Kotlin
run {
    println("Running code block")
}
Sample Program
This program uses the trailing lambda convention to pass a block of code that prints a message multiple times.
Kotlin
fun repeatTask(times: Int, task: () -> Unit) {
    for (i in 1..times) {
        task()
    }
}

fun main() {
    repeatTask(3) {
        println("Hello from lambda!")
    }
}
OutputSuccess
Important Notes
Trailing lambda syntax improves readability especially when lambdas are long or multiline.
You can only use trailing lambda syntax if the lambda is the last parameter in the function.
If there are multiple lambda parameters, trailing lambda can only be used for the last one.
Summary
Trailing lambda lets you put the lambda block outside the parentheses for cleaner code.
It is useful when the last argument of a function is a lambda expression.
This convention is common in Kotlin and helps make code easier to read.