0
0
Kotlinprogramming~15 mins

Trailing lambda convention in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Trailing lambda convention
📖 Scenario: You are creating a simple Kotlin program that uses a function with a lambda parameter to greet users. Kotlin allows a special way to write lambdas called the trailing lambda convention, which makes your code cleaner and easier to read.
🎯 Goal: Learn how to define and call a function with a lambda parameter using the trailing lambda convention in Kotlin.
📋 What You'll Learn
Create a function called greetUser that takes a name string and a lambda called action with no parameters and no return value.
Call the action lambda inside the greetUser function after printing a greeting message.
Call greetUser with the name "Alice" and use the trailing lambda convention to print "Welcome to Kotlin!" inside the lambda.
Print the greeting and the lambda message as output.
💡 Why This Matters
🌍 Real World
Trailing lambda convention is used in Kotlin to write cleaner and more readable code, especially when working with functions that take lambdas, such as event handlers, callbacks, or collection operations.
💼 Career
Understanding trailing lambda syntax is important for Kotlin developers working on Android apps or backend services, as it improves code clarity and is widely used in Kotlin libraries and frameworks.
Progress0 / 4 steps
1
Create the greetUser function
Create a function called greetUser that takes a name parameter of type String and a lambda parameter called action of type () -> Unit. Inside the function, print "Hello, $name!" using println. Do not call the lambda yet.
Kotlin
Need a hint?

Remember to define the lambda parameter action with type () -> Unit and print the greeting inside the function.

2
Call the action lambda inside the function
Inside the greetUser function, after printing the greeting, call the action lambda by writing action().
Kotlin
Need a hint?

Call the lambda by writing action() inside the function body after the greeting.

3
Call greetUser using trailing lambda
Call the greetUser function with the name argument set to "Alice". Use the trailing lambda convention to pass a lambda that prints "Welcome to Kotlin!".
Kotlin
Need a hint?

Use the trailing lambda syntax by placing the lambda block outside the parentheses after the function call.

4
Print the final output
Run the program to print the greeting and the message from the lambda. The output should show Hello, Alice! on one line and Welcome to Kotlin! on the next line.
Kotlin
Need a hint?

Just run the program. The output should show the greeting and the lambda message on separate lines.