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.
fun functionName(param1: Type, lambdaParam: () -> Unit) { // function body } // Calling with trailing lambda: functionName(param1) { // lambda code here }
fun greet(name: String, action: () -> Unit) { println("Hello, $name!") action() } greet("Alice") { println("Welcome!") }
listOf(1, 2, 3).forEach { println(it) }
run { println("Running code block") }
fun repeatTask(times: Int, task: () -> Unit) { for (i in 1..times) { task() } } fun main() { repeatTask(3) { println("Hello from lambda!") } }
trailing lambda convention in Kotlin?list.filter { it > 0 } shows this correctly. list.filter({ it > 0 }) uses lambda inside parentheses (valid but not trailing). list.filter(it > 0) and D are syntax errors.fun greet(action: () -> String) = println(action())
greet { "Hello, Kotlin!" }greet takes a lambda returning a String and prints its result. The call uses trailing lambda syntax. The lambda returns "Hello, Kotlin!" which is printed by println.fun calculate(x: Int, operation: (Int) -> Int): Int {
return operation(x)
}
val result = calculate(5) operation { it * 2 }calculate(5) operation { it * 2 } is invalid because the trailing lambda must be placed immediately after the parentheses without extra tokens. The correct call is calculate(5) { it * 2 }. The word operation should not appear between parentheses and lambda.fun processNumbers(numbers: List<Int>, filter: (Int) -> Boolean, action: (Int) -> Unit) {
for (number in numbers) {
if (filter(number)) action(number)
}
}processNumbers using trailing lambda convention for both lambdas?action is the last lambda, it can be trailing. The first lambda filter must be inside parentheses. processNumbers(listOf(1,2,3), { it > 1 }) { println(it) } correctly places filter inside parentheses and action outside.Pass the test and this pattern moves unknown