androidengineers.Book a session

DSL Creation and Metaprogramming

DSL Scope Control with @DslMarker

article15 minHard

Prevent accidental access to an outer receiver

Nested receiver lambdas can make outer builder functions callable from an inner block. A DSL marker restricts implicit receiver resolution among marked receivers and catches accidental nesting mistakes at compile time.

@DslMarker
annotation class StudyDsl

@StudyDsl
class CourseBuilder {
    fun section(block: SectionBuilder.() -> Unit) { SectionBuilder().block() }
}

@StudyDsl
class SectionBuilder {
    fun lesson(title: String) { require(title.isNotBlank()) }
}

Inside a section block, an unqualified call to the outer course's section operation is restricted. Explicitly qualified access may still be possible; a DSL marker is a clarity mechanism, not a security boundary or complete validation system.

Exercise

Add nested calls demonstrating the accidental outer access, first without the marker and then with it. Keep a small compile-failure example separate from normal runnable examples.

Check: explain why the marker cannot enforce runtime rules such as unique names or a minimum lesson count. Those still belong in builder validation.

Reference: DSL scope control

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
DSL Scope Control with @DslMarker | Kotlin Core Programming | Android Engineers