๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Kotlin Trailing Lambdas

A trailing lambda is a lambda written outside the parentheses of a call. It works when the lambda is the last parameter of the function.

repeat with a trailing lambda

repeat takes a count and a lambda. The lambda trails after the parentheses and runs three times.

fun main() {
    repeat(3) {
        println("Clap")
    }
}

A lambda as the only argument

runTwice takes only a function, so the call drops its parentheses. The lambda sits right after the function name.

fun runTwice(action: () -> Unit) {
    action()
    action()
}

fun main() {
    runTwice {
        println("Tick")
    }
}

One argument inside, one trailing

greet takes a name and a function. The name stays inside the parentheses and the lambda trails outside.

fun greet(name: String, action: (String) -> Unit) {
    action(name)
}

fun main() {
    greet("Mia") { name -> println("Hello, " + name) }
}

it against a named parameter

The first repeat uses it for the step number. The second repeat names the same value index, and both print the same steps.

fun main() {
    repeat(3) { println(it) }
    repeat(3) { index -> println(index) }
}

Example

fun printReport(title: String, rows: (Int) -> String) {
    println(title)
    repeat(3) { println(rows(it)) }
}

fun main() {
    printReport("Scores") { row -> "Row " + row + " ready" }
}

Key points

  • Move the last lambda argument outside the call parentheses.
  • Drop the parentheses entirely when the lambda is the only argument.
  • Other arguments stay inside the parentheses.
  • A single lambda parameter can use the name it.
  • A named parameter replaces it when a clearer name helps reading.

In this example, printReport receives a title and a row builder function. The title stays inside the parentheses at the call, and the builder lambda trails outside. repeat runs the builder for steps 0, 1, and 2.

Note

The trailing shape changes only how the call looks, not what it does.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

When can a lambda trail outside the call parentheses?