0
0
Kotlinprogramming~5 mins

Lambda with receiver concept in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Athis
Bit
Cself
Dreceiver
Which of the following is a correct type for a lambda with receiver that acts on Int and returns String?
A() -> String
B(Int) -> String
CInt.() -> String
DString.() -> Int
What is the main advantage of using lambda with receiver?
AImproves performance by compiling to native code
BAllows calling receiver's methods without naming the receiver
CEnables multi-threading automatically
DPrevents null pointer exceptions
Given val action: String.() -> Unit = { println(this) }, how do you invoke it on "Hello"?
A"Hello".action()
Baction.invoke("Hello")
Caction("Hello")
Daction.call("Hello")
In a lambda with receiver, what does this refer to?
AThe first parameter
BThe lambda itself
CThe outer class instance
DThe receiver object
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.