Bird
Raised Fist0
Kotlinprogramming~20 mins

Lambda with receiver concept in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Lambda Receiver Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of lambda with receiver modifying a StringBuilder
What is the output of this Kotlin code using a lambda with receiver on a StringBuilder?
Kotlin
val result = buildString {
    append("Hello")
    append(", ")
    append("World")
}
println(result)
AHello
BHello World
CHello,World
DHello, World
Attempts:
2 left
💡 Hint
Remember that buildString uses a lambda with receiver on StringBuilder to append text.
❓ Predict Output
intermediate
2:00remaining
Result of applying lambda with receiver on a mutable list
What will be printed by this Kotlin code using a lambda with receiver on a MutableList?
Kotlin
val list = mutableListOf(1, 2, 3)
list.apply {
    add(4)
    remove(2)
}
println(list)
A[1, 2, 3, 4]
B[1, 3]
C[1, 3, 4]
D[4]
Attempts:
2 left
💡 Hint
The apply function uses a lambda with receiver and returns the receiver after applying changes.
🔧 Debug
advanced
2:00remaining
Identify the error in this lambda with receiver usage
What error does this Kotlin code produce?
Kotlin
fun buildMessage(block: StringBuilder.() -> Unit): String {
    val sb = StringBuilder()
    block(sb)
    return sb.toString()
}

val message = buildMessage {
    append("Hi")
    append(123)
}
println(message)
AType mismatch: append(Int) is not available in StringBuilder
BNo error, output: Hi123
CUnresolved reference: append
DRuntimeException: append failed
Attempts:
2 left
💡 Hint
Check if StringBuilder has an append method that accepts Int.
📝 Syntax
advanced
2:00remaining
Which option correctly defines a lambda with receiver type?
Which of these Kotlin declarations correctly defines a lambda with receiver that takes no parameters and returns Unit?
Aval f: String.() -> Unit = { println(this) }
Bval f: (String) -> Unit = { println(this) }
Cval f: () -> String = { this }
Dval f: String -> Unit = { println(this) }
Attempts:
2 left
💡 Hint
A lambda with receiver type uses the syntax ReceiverType.() -> ReturnType.
🚀 Application
expert
3:00remaining
Using lambda with receiver to build a custom HTML tag
Given this Kotlin code, what is the output of the program?
Kotlin
class Tag(val name: String) {
    private val children = mutableListOf<Tag>()
    private var text: String = ""

    fun text(value: String) {
        text = value
    }

    fun tag(name: String, block: Tag.() -> Unit) {
        val t = Tag(name)
        t.block()
        children.add(t)
    }

    override fun toString(): String {
        val builder = StringBuilder()
        builder.append("<$name>")
        if (text.isNotEmpty()) builder.append(text)
        for (c in children) builder.append(c.toString())
        builder.append("</$name>")
        return builder.toString()
    }
}

fun html(block: Tag.() -> Unit): Tag {
    val root = Tag("html")
    root.block()
    return root
}

fun main() {
    val page = html {
        tag("body") {
            tag("h1") {
                text("Welcome")
            }
            tag("p") {
                text("This is a lambda with receiver example.")
            }
        }
    }
    println(page)
}
A<html><body><h1>Welcome</h1><p>This is a lambda with receiver example.</p></body></html>
B<html><body><h1></h1><p></p></body></html>
C<html><body><h1>Welcome<p>This is a lambda with receiver example.</p></h1></body></html>
D<html><body><h1>Welcome</h1><p>This is a lambda with receiver example.</p></body>
Attempts:
2 left
💡 Hint
Look carefully at how children tags are added and how text is appended inside tags.

Practice

(1/5)
1. What is the main benefit of using a lambda with receiver in Kotlin?
easy
A. It disables access to the outer scope variables.
B. It automatically creates a new object for each lambda execution.
C. It forces all lambdas to return Unit type.
D. It allows you to call methods on an object without repeating the object name inside the lambda.

Solution

  1. Step 1: Understand lambda with receiver purpose

    A lambda with receiver lets you write code blocks that behave as if they belong to an object, so you can call its methods directly.
  2. Step 2: Identify the benefit

    This means you don't have to repeat the object name inside the lambda, making code cleaner and easier to read.
  3. Final Answer:

    It allows you to call methods on an object without repeating the object name inside the lambda. -> Option D
  4. Quick Check:

    Lambda with receiver = cleaner calls [OK]
Hint: Remember: receiver means 'this' inside lambda [OK]
Common Mistakes:
  • Thinking it creates new objects automatically
  • Assuming it restricts return types
  • Believing it blocks outer variables
2. Which of the following is the correct syntax to declare a lambda with receiver of type StringBuilder in Kotlin?
easy
A. val lambda: () -> StringBuilder = { append("Hello") }
B. val lambda: (StringBuilder) -> Unit = { append("Hello") }
C. val lambda: StringBuilder.() -> Unit = { append("Hello") }
D. val lambda: StringBuilder -> Unit = { append("Hello") }

Solution

  1. Step 1: Recall lambda with receiver syntax

    A lambda with receiver is declared by specifying the receiver type followed by a dot and then the function type, like StringBuilder.() -> Unit.
  2. Step 2: Match syntax with options

    val lambda: StringBuilder.() -> Unit = { append("Hello") } matches this syntax and uses append("Hello") inside the lambda, which is valid for StringBuilder.
  3. Final Answer:

    val lambda: StringBuilder.() -> Unit = { append("Hello") } -> Option C
  4. Quick Check:

    Receiver syntax = Type.() -> ReturnType [OK]
Hint: Receiver lambdas use Type.() -> ReturnType syntax [OK]
Common Mistakes:
  • Confusing parameter lambdas with receiver lambdas
  • Missing the dot after the receiver type
  • Using arrow without parentheses
3. What is the output of the following Kotlin code?
val buildString: StringBuilder.() -> Unit = {
    append("Hi")
    append(", ")
    append("there!")
}

val result = StringBuilder().apply(buildString).toString()
println(result)
medium
A. Compilation error
B. Hi, there!
C. Hi there!
D. StringBuilder@<hashcode>

Solution

  1. Step 1: Understand the lambda with receiver usage

    The lambda buildString is a StringBuilder receiver lambda that appends "Hi", ", ", and "there!" to the StringBuilder.
  2. Step 2: Apply lambda and convert to string

    The apply function runs the lambda on a new StringBuilder instance, then toString() converts it to the string "Hi, there!".
  3. Final Answer:

    Hi, there! -> Option B
  4. Quick Check:

    apply + receiver lambda = built string [OK]
Hint: apply runs lambda on object, returns object [OK]
Common Mistakes:
  • Expecting default toString output of StringBuilder
  • Missing commas in output
  • Thinking lambda returns string directly
4. Identify the error in this Kotlin code using a lambda with receiver:
val printLength: String.() -> Unit = {
    println(length())
}

"Hello".printLength()
medium
A. Cannot call length() as a function; length is a property.
B. Lambda with receiver must return a value.
C. String cannot be a receiver type.
D. Missing parentheses when calling printLength.

Solution

  1. Step 1: Check usage of length inside lambda

    In Kotlin, length is a property of String, not a function, so calling length() causes an error.
  2. Step 2: Verify other parts

    The lambda correctly uses String as receiver and returns Unit, and calling printLength without parentheses is valid syntax.
  3. Final Answer:

    Cannot call length() as a function; length is a property. -> Option A
  4. Quick Check:

    Properties accessed without () [OK]
Hint: Remember: properties have no parentheses [OK]
Common Mistakes:
  • Using parentheses with properties
  • Thinking receiver type can't be String
  • Forgetting lambda return type can be Unit
5. You want to create a function buildHtml that uses a lambda with receiver to build an HTML string with nested tags. Which approach correctly uses lambda with receiver to achieve this?
fun buildHtml(block: StringBuilder.() -> Unit): String {
    val sb = StringBuilder()
    sb.block()
    return sb.toString()
}

val html = buildHtml {
    append("")
    append("")
    append("Hello")
    append("")
    append("")
}
println(html)
hard
A. This code correctly uses a lambda with receiver to build the HTML string.
B. The lambda should have a receiver of type HtmlBuilder, not StringBuilder.
C. You must return the lambda result explicitly inside buildHtml.
D. The lambda cannot be called with sb.block(); use block(sb) instead.

Solution

  1. Step 1: Analyze the function signature and call

    The function buildHtml takes a lambda with receiver StringBuilder.() -> Unit and calls it on sb using sb.block(), which is correct syntax.
  2. Step 2: Check the lambda body and return

    The lambda appends HTML tags to StringBuilder, and the function returns the built string with sb.toString(), which is the expected behavior.
  3. Final Answer:

    This code correctly uses a lambda with receiver to build the HTML string. -> Option A
  4. Quick Check:

    Lambda with receiver called on object = correct [OK]
Hint: Call receiver lambda with object.lambda() syntax [OK]
Common Mistakes:
  • Confusing lambda with receiver and lambda with parameter
  • Forgetting to call lambda on the object
  • Expecting lambda to return string directly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard