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.() -> StringInside
formatter, convert the string to uppercase and add an exclamation mark at the endCall
formatter on text and store the result in formattedTextPrint 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