Bird
Raised Fist0
Kotlinprogramming~20 mins

DSL scope control with @DslMarker in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
DSL Scope Master
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 code with @DslMarker?

Consider this Kotlin DSL code using @DslMarker to control scope. What will be printed when running buildHtml()?

Kotlin
import kotlin.text.StringBuilder

@DslMarker
annotation class HtmlTagMarker

@HtmlTagMarker
class Html {
    private val children = mutableListOf<Any>()
    fun body(init: Body.() -> Unit) {
        val body = Body()
        body.init()
        children.add(body)
    }
    override fun toString() = children.joinToString(separator = "\n")
}

@HtmlTagMarker
class Body {
    private val children = mutableListOf<String>()
    fun p(text: String) {
        children.add("<p>$text</p>")
    }
    override fun toString() = children.joinToString(separator = "\n")
}

fun buildHtml(): String {
    val html = Html()
    html.body {
        p("Hello")
        // The following line would cause a compile error if uncommented:
        // this@Html.body { p("World") }
    }
    return html.toString()
}

fun main() {
    println(buildHtml())
}
A<p>Hello</p>
B<body><p>Hello</p></body>
CHello
D<html><body><p>Hello</p></body></html>
Attempts:
2 left
💡 Hint

Look at how toString() is implemented for Html and Body. The Html class collects Body objects, and Body collects paragraph strings.

🧠 Conceptual
intermediate
1:30remaining
What is the main purpose of the @DslMarker annotation in Kotlin DSLs?

Why do Kotlin DSL authors use the @DslMarker annotation on their DSL marker annotations?

ATo prevent implicit receivers from different DSL scopes from being accessed simultaneously, avoiding scope ambiguity.
BTo automatically generate builder classes for the DSL elements.
CTo enable multi-threading support in DSL builders.
DTo allow DSL functions to be called without parentheses.
Attempts:
2 left
💡 Hint

Think about how nested DSL blocks might have multiple receivers with similar function names.

🔧 Debug
advanced
2:00remaining
Why does this Kotlin DSL code cause a compile error related to @DslMarker?

Examine the code below. Why does the call to p("World") inside the nested body cause a compile error?

Kotlin
import kotlin.text.StringBuilder

@DslMarker
annotation class HtmlTagMarker

@HtmlTagMarker
class Html {
    fun body(init: Body.() -> Unit) {
        val body = Body()
        body.init()
    }
}

@HtmlTagMarker
class Body {
    fun p(text: String) {}
    fun body(init: Body.() -> Unit) {}
}

fun main() {
    val html = Html()
    html.body {
        p("Hello")
        body {
            p("World") // Compile error here
        }
    }
}
ABecause the Body class does not implement the p function correctly.
BBecause @DslMarker prevents accessing the outer Html receiver's body function inside the nested body block.
CBecause nested body calls are not allowed in Kotlin DSLs.
DBecause the p function is private and cannot be accessed.
Attempts:
2 left
💡 Hint

Consider how @DslMarker restricts implicit receivers in nested DSL scopes.

📝 Syntax
advanced
1:30remaining
Which option correctly applies @DslMarker to create a DSL marker annotation?

Choose the correct Kotlin code snippet that defines a DSL marker annotation named MyDslMarker and applies it to two DSL classes BuilderA and BuilderB.

A
annotation class MyDslMarker

@DslMarker
class BuilderA

@DslMarker
class BuilderB
B
annotation class MyDslMarker

@MyDslMarker
annotation class BuilderA

@MyDslMarker
annotation class BuilderB
C
import kotlin.DslMarker

@DslMarker
annotation class MyDslMarker

@MyDslMarker
class BuilderA

@MyDslMarker
class BuilderB
D
import kotlin.DslMarker

@DslMarker
class MyDslMarker

@MyDslMarker
class BuilderA

@MyDslMarker
class BuilderB
Attempts:
2 left
💡 Hint

Remember that @DslMarker must annotate an annotation class, not a regular class.

🚀 Application
expert
2:30remaining
How many items are in the resulting list after running this Kotlin DSL code with @DslMarker?

Given the following Kotlin DSL code using @DslMarker, how many items does the items list contain after buildList() is called?

Kotlin
import kotlin.collections.mutableListOf

@DslMarker
annotation class ListDsl

@ListDsl
class ListBuilder {
    val items = mutableListOf<String>()
    fun item(value: String) {
        items.add(value)
    }
    fun nested(init: NestedBuilder.() -> Unit) {
        val nested = NestedBuilder()
        nested.init()
        items.addAll(nested.items)
    }
}

@ListDsl
class NestedBuilder {
    val items = mutableListOf<String>()
    fun item(value: String) {
        items.add(value)
    }
}

fun buildList(): List<String> {
    val builder = ListBuilder()
    builder.item("A")
    builder.nested {
        item("B")
        item("C")
    }
    return builder.items
}

fun main() {
    println(buildList())
}
A4
B2
C1
D3
Attempts:
2 left
💡 Hint

Count all items added to the main builder's list, including those added from the nested builder.

Practice

(1/5)
1. What is the main purpose of the @DslMarker annotation in Kotlin DSLs?
easy
A. To limit function visibility and prevent accidental calls to outer DSL scopes inside nested blocks.
B. To mark a function as deprecated in DSL usage.
C. To automatically generate DSL builder classes.
D. To enable inline functions in DSL builders.

Solution

  1. Step 1: Understand DSL nesting problem

    In nested DSL blocks, functions from outer scopes can be accidentally called inside inner blocks, causing confusion.
  2. Step 2: Role of @DslMarker

    @DslMarker annotation marks DSL builder classes to restrict visibility of outer scope functions inside nested DSL blocks, preventing accidental calls.
  3. Final Answer:

    To limit function visibility and prevent accidental calls to outer DSL scopes inside nested blocks. -> Option A
  4. Quick Check:

    @DslMarker controls scope visibility = A [OK]
Hint: Remember: @DslMarker hides outer DSL functions inside nested blocks [OK]
Common Mistakes:
  • Thinking @DslMarker generates code automatically
  • Confusing @DslMarker with deprecation annotations
  • Assuming @DslMarker enables inline functions
2. Which of the following is the correct way to define a DSL marker annotation in Kotlin?
easy
A. fun @DslMarker MyDslMarker() {}"
B. annotation class DslMarker
C. @DslMarker fun MyDslMarker() {}
D. @DslMarker annotation class MyDslMarker

Solution

  1. Step 1: Recall syntax for DSL marker annotation

    DSL marker annotations must be annotated with @DslMarker and declared as annotation classes.
  2. Step 2: Identify correct syntax

    @DslMarker annotation class MyDslMarker correctly declares an annotation class with @DslMarker annotation: @DslMarker annotation class MyDslMarker.
  3. Final Answer:

    @DslMarker annotation class MyDslMarker -> Option D
  4. Quick Check:

    DSL marker annotation syntax = A [OK]
Hint: DSL marker annotations are annotation classes with @DslMarker prefix [OK]
Common Mistakes:
  • Defining DSL marker as a function instead of annotation class
  • Missing the @DslMarker annotation on the annotation class
  • Using incorrect placement of @DslMarker keyword
3. Consider the following Kotlin DSL code snippet with two DSL marker annotations applied:
@DslMarker
annotation class FirstDsl

@DslMarker
annotation class SecondDsl

@FirstDsl
class BuilderA {
    fun a() = println("A")
    fun buildB(block: BuilderB.() -> Unit) {
        BuilderB().apply(block)
    }
}

@SecondDsl
class BuilderB {
    fun b() = println("B")
    fun buildA(block: BuilderA.() -> Unit) {
        BuilderA().apply(block)
    }
}

fun main() {
    BuilderA().apply {
        a()
        buildB {
            b()
            // Which call is allowed here?
            // a() or b() or both?
        }
    }
}
Which function call is allowed inside the buildB block?
medium
A. Only a() is allowed; b() is not visible.
B. Both a() and b() are allowed inside buildB block.
C. Only b() is allowed; a() is not visible due to DSL marker scope control.
D. Neither a() nor b() is allowed inside buildB block.

Solution

  1. Step 1: Understand effect of multiple @DslMarker annotations

    Each DSL marker annotation restricts visibility of outer scope functions from classes annotated with different DSL markers.
  2. Step 2: Analyze nested block visibility

    Inside buildB block (BuilderB scope), only b() is visible. The a() function from BuilderA is hidden due to different DSL markers.
  3. Final Answer:

    Only b() is allowed; a() is not visible due to DSL marker scope control. -> Option C
  4. Quick Check:

    Different DSL markers hide outer scope functions = C [OK]
Hint: Different DSL markers hide outer scope functions inside nested blocks [OK]
Common Mistakes:
  • Assuming all functions from outer scopes are visible
  • Ignoring effect of multiple DSL markers
  • Confusing which DSL marker applies where
4. Given the following Kotlin DSL code, what is the error and how to fix it?
@DslMarker
annotation class MyDsl

@MyDsl
class Outer {
    fun outerFun() = println("Outer")
    fun inner(block: Inner.() -> Unit) {
        Inner().apply(block)
    }
}

@MyDsl
class Inner {
    fun innerFun() = println("Inner")
}

fun main() {
    Outer().apply {
        outerFun()
        inner {
            outerFun() // Error here
            innerFun()
        }
    }
}
medium
A. Error: innerFun() is not visible; fix by removing @MyDsl annotation.
B. Error: Cannot call outerFun() inside inner block due to DSL marker scope control; fix by qualifying with this@Outer.outerFun().
C. Error: inner block is not called; fix by changing Inner().block() to Inner().apply(block).
D. No error; code runs fine.

Solution

  1. Step 1: Identify cause of error

    Inside the inner block, outerFun() is not directly visible because @MyDsl restricts access to outer scope functions.
  2. Step 2: Fix by explicit qualification

    Use explicit label this@Outer.outerFun() to call the outer function inside the inner block, bypassing DSL marker restriction.
  3. Final Answer:

    Error: Cannot call outerFun() inside inner block due to DSL marker scope control; fix by qualifying with this@Outer.outerFun(). -> Option B
  4. Quick Check:

    Use explicit this@Outer to access outer functions [OK]
Hint: Use this@Outer to call outer functions blocked by DSL marker [OK]
Common Mistakes:
  • Removing @DslMarker annotation instead of qualifying call
  • Ignoring the need for explicit receiver labels
  • Assuming innerFun() visibility causes error
5. You want to create a Kotlin DSL for building HTML-like structures with nested tags. You define two builder classes HtmlBuilder and BodyBuilder, both annotated with the same @DslMarker annotation. How does using @DslMarker help prevent mistakes when writing nested DSL code like html { body { div { ... } } }?
hard
A. It prevents calling functions from HtmlBuilder inside BodyBuilder blocks unless explicitly qualified, avoiding accidental outer scope calls.
B. It automatically generates HTML tags for each builder class.
C. It allows calling any function from HtmlBuilder inside BodyBuilder without restrictions.
D. It disables nested DSL blocks to simplify code.

Solution

  1. Step 1: Understand nested DSL structure

    In nested DSLs like HTML, inner blocks (BodyBuilder) are inside outer blocks (HtmlBuilder).
  2. Step 2: Role of @DslMarker in nested builders

    @DslMarker annotation restricts visibility of outer builder functions inside inner builder blocks, preventing accidental calls to outer scope functions without explicit qualification.
  3. Final Answer:

    It prevents calling functions from HtmlBuilder inside BodyBuilder blocks unless explicitly qualified, avoiding accidental outer scope calls. -> Option A
  4. Quick Check:

    @DslMarker hides outer builder functions inside nested blocks [OK]
Hint: Use @DslMarker to avoid accidental outer scope calls in nested DSLs [OK]
Common Mistakes:
  • Thinking @DslMarker generates code automatically
  • Assuming all functions remain visible inside nested blocks
  • Believing @DslMarker disables nesting
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