0
0
Kotlinprogramming~15 mins

Lambda with receiver concept in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Lambda with receiver concept
📖 Scenario: Imagine you want to build a simple text formatter that can change the case of a string and add punctuation. Using Kotlin's lambda with receiver, you can create a neat way to apply these changes inside a block that feels like working directly on the string.
🎯 Goal: You will create a lambda with receiver that modifies a string by changing its case and adding punctuation, then apply it to a sample string and print the result.
📋 What You'll Learn
Create a variable called text with the value "hello kotlin"
Create a lambda with receiver called formatter of type String.() -> String
Inside formatter, convert the string to uppercase and add an exclamation mark at the end
Call formatter on text and store the result in formattedText
Print the value of formattedText
💡 Why This Matters
🌍 Real World
Lambda with receiver is useful in Kotlin DSLs (domain-specific languages) and builder patterns where you want to write clean and readable code that looks like it is working inside an object.
💼 Career
Understanding lambda with receiver helps you work with Kotlin libraries and frameworks that use this feature, such as Android development with Kotlin, making your code more concise and expressive.
Progress0 / 4 steps
1
Create the initial string
Create a variable called text and set it to the string "hello kotlin".
Kotlin
Need a hint?

Use val text = "hello kotlin" to create the string variable.

2
Create the lambda with receiver
Create a lambda with receiver called formatter of type String.() -> String. Inside it, convert the string to uppercase and add an exclamation mark at the end.
Kotlin
Need a hint?

Define formatter as val formatter: String.() -> String = { this.uppercase() + "!" }.

3
Apply the lambda with receiver
Call the lambda formatter on the variable text and store the result in a variable called formattedText.
Kotlin
Need a hint?

Use val formattedText = text.formatter() to apply the lambda.

4
Print the formatted text
Print the value of the variable formattedText.
Kotlin
Need a hint?

Use println(formattedText) to display the result.