Recall & Review
beginner
What is a lambda with receiver in Kotlin?
A lambda with receiver is a special kind of lambda where you can call methods and access properties of a receiver object directly inside the lambda, without using its name.
Click to reveal answer
intermediate
How do you define a lambda with receiver type in Kotlin?
You define it by specifying the receiver type before the lambda parameters, like
ReceiverType.() -> ReturnType. For example, String.() -> Int means a lambda that acts on a String receiver and returns an Int.Click to reveal answer
beginner
What is the benefit of using a lambda with receiver?
It lets you write cleaner and more readable code by calling receiver's methods directly inside the lambda, similar to how you use
this in a class, reducing repetition.Click to reveal answer
intermediate
How do you call a lambda with receiver?
You call it by providing the receiver object and then invoking the lambda on it. For example,
val result = receiver.lambda() where lambda is a lambda with receiver.Click to reveal answer
beginner
Example: What does this Kotlin code print?<br>
val greet: String.() -> String = { "Hello, $this!" }
println("World".greet())It prints
Hello, World! because the lambda uses the receiver String ("World") as this and returns the greeting.Click to reveal answer
What keyword represents the receiver object inside a lambda with receiver?
✗ Incorrect
Inside a lambda with receiver, the receiver object is accessed using the keyword
this.Which of the following is a correct type for a lambda with receiver that acts on Int and returns String?
✗ Incorrect
The correct syntax for a lambda with receiver is
ReceiverType.() -> ReturnType, so Int.() -> String is correct.What is the main advantage of using lambda with receiver?
✗ Incorrect
Lambda with receiver lets you call methods and properties of the receiver directly, making code cleaner.
Given
val action: String.() -> Unit = { println(this) }, how do you invoke it on "Hello"?✗ Incorrect
You invoke a lambda with receiver by calling it on the receiver object, like
"Hello".action().In a lambda with receiver, what does
this refer to?✗ Incorrect
this inside a lambda with receiver refers to the receiver object on which the lambda is called.Explain what a lambda with receiver is and how it differs from a regular lambda.
Think about how you can call methods inside the lambda without naming the object.
You got /4 concepts.
Describe how to define and invoke a lambda with receiver in Kotlin with a simple example.
Use a String receiver and a lambda that returns a greeting.
You got /4 concepts.