0
0
Kotlinprogramming~5 mins

Lambda with receiver concept in Kotlin

Choose your learning style9 modes available
Introduction
A lambda with receiver lets you write code that feels like it belongs to an object, making your code cleaner and easier to read.
When you want to build or configure objects in a simple and readable way.
When you want to create a small block of code that works directly with an object without repeating its name.
When you want to write DSLs (Domain Specific Languages) that look like natural language.
When you want to group related operations on an object inside a neat block.
Syntax
Kotlin
val lambdaName: ReceiverType.() -> ReturnType = {
    // code using 'this' as ReceiverType
}
The receiver type is the object on which the lambda operates, accessed as 'this' inside the lambda.
You call the lambda on an instance of the receiver type, like: instance.lambdaName()
Examples
A lambda with receiver on String that returns a greeting message using the string itself.
Kotlin
val greet: String.() -> String = {
    "Hello, $this!"
}

val message = "World".greet()
A lambda with receiver on StringBuilder that adds an exclamation mark to the string builder.
Kotlin
val addExclamation: StringBuilder.() -> Unit = {
    append("!")
}

val sb = StringBuilder("Hi")
sb.addExclamation()
Sample Program
This program uses a lambda with receiver on StringBuilder to build a greeting message step by step inside the lambda. Then it prints the final message.
Kotlin
fun main() {
    val buildMessage: StringBuilder.() -> Unit = {
        append("Hello")
        append(", ")
        append("Kotlin")
        append("!")
    }

    val messageBuilder = StringBuilder()
    messageBuilder.buildMessage()
    println(messageBuilder.toString())
}
OutputSuccess
Important Notes
Inside the lambda, you can call the receiver's methods directly without using its name.
You can use 'this' explicitly if you want, but it's optional.
Lambdas with receiver are useful for creating clean and readable code blocks that work on objects.
Summary
A lambda with receiver lets you write code blocks that act like they belong to an object.
It helps make code cleaner by avoiding repeated object names.
You use it by defining a lambda with a receiver type and calling it on an instance of that type.