0
0
Kotlinprogramming~10 mins

DSL scope control with @DslMarker 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 a DSL marker annotation.

Kotlin
import kotlin.annotation.AnnotationRetention.RUNTIME
import kotlin.annotation.AnnotationTarget.CLASS

@DslMarker
annotation class [1]
Drag options to blanks, or click blank then click option'
ADslControl
BDslMarker
CMyDsl
DDslScope
Attempts:
3 left
💡 Hint
Common Mistakes
Using @DslMarker as the annotation name instead of defining a custom annotation.
Forgetting to add @DslMarker before the annotation class.
2fill in blank
medium

Complete the code to apply the DSL marker annotation to a class.

Kotlin
@[1]
class HtmlBuilder {
    fun body(init: BodyBuilder.() -> Unit) {}
}
Drag options to blanks, or click blank then click option'
ADslMarker
BMyDsl
CDslScope
DDslControl
Attempts:
3 left
💡 Hint
Common Mistakes
Using @DslMarker instead of the custom annotation name.
Not annotating the class at all.
3fill in blank
hard

Fix the error in the code by completing the blank to prevent implicit receiver conflicts.

Kotlin
@MyDsl
class BodyBuilder {
    fun div(init: DivBuilder.() -> Unit) {}

    fun text(value: String) {
        println([1])
    }
}
Drag options to blanks, or click blank then click option'
Avalue
Bthis.value
Ctext
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'this.value' which may cause confusion with receiver scope.
Using 'init' which is a lambda, not the string value.
4fill in blank
hard

Fill both blanks to define two DSL builder classes with the DSL marker annotation.

Kotlin
@[1]
class DivBuilder {
    fun span(init: SpanBuilder.() -> Unit) {}
}

@[2]
class SpanBuilder {}
Drag options to blanks, or click blank then click option'
AMyDsl
BDslMarker
CDslScope
DDslControl
Attempts:
3 left
💡 Hint
Common Mistakes
Using different annotations for each class.
Using @DslMarker instead of the custom annotation.
5fill in blank
hard

Fill all three blanks to create a DSL builder function with proper scope control.

Kotlin
fun html(init: [1].() -> Unit) {
    val builder = [2]()
    builder.[3]()
}
Drag options to blanks, or click blank then click option'
AHtmlBuilder
Cinit
DBodyBuilder
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for receiver and instance.
Not calling the lambda parameter.