0
0
Kotlinprogramming~10 mins

Extensions for DSL building in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define an extension function named greet for the String class that prints a greeting message.

Kotlin
fun String.[1]() {
    println("Hello, $this!")
}

"World".greet()
Drag options to blanks, or click blank then click option'
Awelcome
Bhello
CsayHello
Dgreet
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different function name than the one called on the string.
Forgetting to define the function as an extension (missing 'String.' before the function name).
2fill in blank
medium

Complete the code to create a DSL builder function html that takes a lambda with receiver of type HtmlBuilder.

Kotlin
fun html(block: [1].() -> Unit) {
    val builder = HtmlBuilder()
    builder.block()
    println(builder.result)
}
Drag options to blanks, or click blank then click option'
AHtmlBuilder
BString
CInt
DUnit
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong receiver type like String or Int.
Not matching the receiver type with the builder instance.
3fill in blank
hard

Fix the error in the extension function that adds an li element inside a ul builder.

Kotlin
class UlBuilder {
    val items = mutableListOf<String>()
    fun li(text: String) {
        items.add(text)
    }
}

fun UlBuilder.[1](text: String) {
    li(text)
}
Drag options to blanks, or click blank then click option'
Ali
BlistItem
Citem
DaddItem
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different function name that does not match the existing method.
Causing ambiguity by defining a different name for the same action.
4fill in blank
hard

Fill both blanks to create a DSL function body inside HtmlBuilder that takes a lambda with receiver BodyBuilder.

Kotlin
class HtmlBuilder {
    var result = ""
    fun [1](block: [2].() -> Unit) {
        val bodyBuilder = BodyBuilder()
        bodyBuilder.block()
        result += bodyBuilder.content
    }
}
Drag options to blanks, or click blank then click option'
Abody
Bhead
CBodyBuilder
DHeadBuilder
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'head' or 'HeadBuilder' instead of 'body' and 'BodyBuilder'.
Mixing function name and receiver type.
5fill in blank
hard

Fill all three blanks to create a DSL function div inside BodyBuilder that takes a lambda with receiver DivBuilder and appends the result.

Kotlin
class BodyBuilder {
    var content = ""
    fun [1](block: [2].() -> Unit) {
        val divBuilder = [3]()
        divBuilder.block()
        content += divBuilder.html
    }
}
Drag options to blanks, or click blank then click option'
Adiv
BDivBuilder
DBodyBuilder
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for function, receiver, or instance.
Confusing BodyBuilder with DivBuilder.