0
0
Kotlinprogramming~20 mins

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

Choose your learning style9 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.