Bird
Raised Fist0
Kotlinprogramming~20 mins

Extensions for DSL building in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
DSL Mastery in Kotlin
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Kotlin DSL extension code?

Consider the following Kotlin code that uses extension functions to build a simple DSL for HTML-like tags. What will be printed when this code runs?

Kotlin
class Tag(val name: String) {
    private val children = mutableListOf<Tag>()
    fun tag(name: String, init: Tag.() -> Unit) {
        val t = Tag(name)
        t.init()
        children.add(t)
    }
    override fun toString(): String {
        val inner = children.joinToString("") { it.toString() }
        return "<$name>$inner</$name>"
    }
}

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

fun main() {
    val result = html {
        tag("body") {
            tag("p") {}
        }
    }
    println(result)
}
A<html><body><p></p></body></html>
B<html><body></body><p></p></html>
C<html><p></p><body></body></html>
DCompilation error due to missing return type
Attempts:
2 left
💡 Hint

Look at how the tag function adds children inside the current tag.

🧠 Conceptual
intermediate
1:30remaining
Which Kotlin feature allows building DSLs with extension functions?

In Kotlin, what feature primarily enables the creation of DSLs using extension functions?

AData classes with default parameters
BHigher-order functions with lambda receivers
CInline classes with operator overloading
DSealed classes with companion objects
Attempts:
2 left
💡 Hint

Think about how lambdas can be called with a receiver object.

🔧 Debug
advanced
2:00remaining
Why does this Kotlin DSL code throw a NullPointerException?

Examine the Kotlin DSL code below. It throws a NullPointerException at runtime. What is the cause?

Kotlin
class Builder {
    var text: String? = null
    fun build(): String {
        return text!!.toUpperCase()
    }
}

fun buildString(init: Builder.() -> Unit): String {
    val builder = Builder()
    builder.init()
    return builder.build()
}

fun main() {
    val result = buildString {
        // text is not set here
    }
    println(result)
}
AThe 'toUpperCase()' method is deprecated and causes an error
BThe 'buildString' function is missing a return statement
CThe 'init' lambda is not called on the Builder instance
DThe 'text' property is never initialized before calling 'build()'
Attempts:
2 left
💡 Hint

Check the value of 'text' before calling toUpperCase().

📝 Syntax
advanced
1:30remaining
Which option correctly defines an extension function for DSL building in Kotlin?

Which of the following Kotlin code snippets correctly defines an extension function named section for a class Document that takes a lambda with receiver?

Afun section(Document.init: () -> Unit) { init() }
Bfun Document.section(init: () -> Unit) { this.init() }
Cfun Document.section(init: Document.() -> Unit) { init() }
Dfun Document.section(init: Document) -> Unit { init() }
Attempts:
2 left
💡 Hint

Remember the syntax for extension functions with lambda receivers.

🚀 Application
expert
2:30remaining
How many tags are created by this Kotlin DSL code?

Given the Kotlin DSL code below, how many Tag instances are created in total?

Kotlin
class Tag(val name: String) {
    val children = mutableListOf<Tag>()
    fun tag(name: String, init: Tag.() -> Unit = {}) {
        val t = Tag(name)
        t.init()
        children.add(t)
    }
}

fun main() {
    val root = Tag("root")
    root.tag("a") {
        tag("b") {
            tag("c")
        }
        tag("d")
    }
    root.tag("e")
}
A6
B5
C4
D7
Attempts:
2 left
💡 Hint

Count the root and all nested tags created by each tag call.

Practice

(1/5)
1. What is the main purpose of using extensions in Kotlin for DSL building?
easy
A. To add new functions to existing classes without modifying their source code
B. To create new classes from scratch
C. To change the behavior of existing functions permanently
D. To restrict access to class members

Solution

  1. Step 1: Understand what extensions do

    Extensions allow adding new functions to existing classes without changing their original code.
  2. Step 2: Relate to DSL building

    This helps create readable DSLs by extending classes with custom functions.
  3. Final Answer:

    To add new functions to existing classes without modifying their source code -> Option A
  4. Quick Check:

    Extensions add functions without modifying classes [OK]
Hint: Extensions add functions without changing original classes [OK]
Common Mistakes:
  • Thinking extensions create new classes
  • Believing extensions permanently change existing functions
  • Confusing extensions with access control
2. Which of the following is the correct syntax to define an extension function greet for the String class in Kotlin?
easy
A. extension fun String greet() { println("Hello") }
B. fun greet(String) { println("Hello") }
C. fun String.greet() { println("Hello") }
D. fun greet() String { println("Hello") }

Solution

  1. Step 1: Recall extension function syntax

    Extension functions are declared with fun ClassName.functionName().
  2. Step 2: Match syntax to options

    fun String.greet() { println("Hello") } uses fun String.greet(), which is correct syntax.
  3. Final Answer:

    fun String.greet() { println("Hello") } -> Option C
  4. Quick Check:

    Extension syntax = fun ClassName.functionName() [OK]
Hint: Extension syntax: fun ClassName.functionName() [OK]
Common Mistakes:
  • Placing class name as parameter instead of receiver
  • Using 'extension' keyword which doesn't exist
  • Incorrect function return type placement
3. What will be the output of the following Kotlin code?
class Box(var content: String)

fun Box.describe() = "Box contains: $content"

fun main() {
    val box = Box("Apples")
    println(box.describe())
}
medium
A. Box contains: Apples
B. Box contains: content
C. Compilation error
D. Box@<memory_address>

Solution

  1. Step 1: Understand the extension function

    The extension function describe returns a string with the content property of Box.
  2. Step 2: Check the main function output

    Creating Box("Apples") and calling describe() prints "Box contains: Apples".
  3. Final Answer:

    Box contains: Apples -> Option A
  4. Quick Check:

    Extension uses property value correctly [OK]
Hint: Extension functions use class properties directly [OK]
Common Mistakes:
  • Expecting 'content' literal instead of property value
  • Confusing extension with overriding toString()
  • Thinking it prints memory address
4. Identify the error in this Kotlin code snippet that tries to build a simple DSL using extensions:
class Menu {
    val items = mutableListOf<String>()
}

fun Menu.addItem(name: String) {
    items.add(name)
}

fun buildMenu(block: Menu.() -> Unit): Menu {
    val menu = Menu()
    block(menu)
    return menu
}

fun main() {
    val menu = buildMenu {
        addItem("Home")
        addItem("About")
    }
    println(menu.items)
}
medium
A. The extension function addItem should be inside the Menu class
B. The block should be called with menu.block() instead of block(menu)
C. MutableList should be immutableList
D. No error, code runs correctly

Solution

  1. Step 1: Understand the block parameter type

    The block is a lambda with receiver: Menu.() -> Unit, so it should be called as menu.block().
  2. Step 2: Identify the call mistake

    The code calls block(menu), which treats block as a normal function, causing an error.
  3. Final Answer:

    The block should be called with menu.block() instead of block(menu) -> Option B
  4. Quick Check:

    Lambda with receiver called as receiver.lambda() [OK]
Hint: Call lambdas with receiver as receiver.lambda() [OK]
Common Mistakes:
  • Calling lambda with receiver as normal function
  • Placing extension function inside class unnecessarily
  • Confusing mutable and immutable lists
5. Given the following Kotlin DSL code, what is the output?
class Html {
    val children = mutableListOf<String>()
}

fun Html.body(block: Html.() -> Unit) {
    this.block()
}

fun Html.p(text: String) {
    children.add("

$text

") } fun html(block: Html.() -> Unit): Html { val html = Html() html.block() return html } fun main() { val page = html { body { p("Hello") p("World") } } println(page.children) }
hard
A. Compilation error due to missing body class
B. []
C. ["

Hello

World

"]
D. ["

Hello

", "

World

"]

Solution

  1. Step 1: Trace the DSL calls

    The html function creates an Html object and calls body extension, which calls p twice adding paragraphs to children.
  2. Step 2: Check the children list content

    Both p calls add strings "

    Hello

    " and "

    World

    " to the children list.
  3. Final Answer:

    ["

    Hello

    ", "

    World

    "]
    -> Option D
  4. Quick Check:

    Extensions build nested structure as list of strings [OK]
Hint: Extensions add elements to list step-by-step [OK]
Common Mistakes:
  • Expecting nested tags as single string
  • Assuming body creates separate object
  • Thinking code causes compilation error
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