0
0
Kotlinprogramming~10 mins

Trailing lambda convention in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Trailing lambda convention
Call function with lambda
Is lambda last argument?
NoCall normally
Yes
Use trailing lambda syntax
Execute lambda block
Return from function
The trailing lambda convention lets you pass a lambda outside the parentheses if it's the last argument, making code cleaner.
Execution Sample
Kotlin
fun greet(action: () -> Unit) {
    println("Hello")
    action()
}

greet {
    println("Welcome!")
}
Defines a function taking a lambda and calls it using trailing lambda syntax.
Execution Table
StepActionOutputNotes
1Call greet with trailing lambdaLambda passed outside parentheses
2Print "Hello"HelloFirst print in greet()
3Execute lambda blockWelcome!Lambda prints "Welcome!"
4Return from greetFunction ends
💡 Function greet completes after executing lambda passed as trailing argument
Variable Tracker
VariableStartAfter greet callAfter lambda executionFinal
actionN/Alambda functionexecutedN/A
Key Moments - 2 Insights
Why can we write the lambda outside the parentheses?
Because the lambda is the last argument, Kotlin allows trailing lambda syntax to improve readability, as shown in step 1 of the execution_table.
What happens if the lambda is not the last argument?
You must pass the lambda inside the parentheses; trailing lambda syntax only works if the lambda is the last argument.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed at step 3?
A"Hello"
B"Welcome!"
CNothing
DAn error
💡 Hint
Check the Output column at step 3 in the execution_table
At which step does the lambda function get executed?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the Action column in the execution_table for when the lambda block runs
If the lambda was not the last argument, how would the call change?
ALambda would still be outside parentheses
BLambda would be omitted
CLambda must be inside parentheses
DFunction call would fail
💡 Hint
Refer to key_moments about lambda position and syntax
Concept Snapshot
Trailing lambda convention in Kotlin:
- If the last argument is a lambda, write it outside parentheses.
- Makes code cleaner and more readable.
- Only works if lambda is last argument.
- Example: greet { println("Welcome!") }
Full Transcript
This example shows Kotlin's trailing lambda convention. The function greet takes a lambda as its only argument. When calling greet, the lambda is written outside the parentheses, making the call cleaner. Execution steps show printing "Hello", then running the lambda which prints "Welcome!". The lambda variable is assigned at call and executed inside the function. This convention only works if the lambda is the last argument. If not, the lambda must be inside the parentheses.