https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jason5lee

07/27/2022, 7:43 AM
I'm writing a DSL. It's something like this.
Copy code
class Scope {
    fun method(block: () -> Unit) {}
}

fun scope(block: Scope.() -> Unit) {}

fun main() {
    scope {
        method {
            method {  } // I want to disallow using the scope inside the method
        }
    }
}
I want to disallow calling method on the
Scope
inside the
method
. I know I can have a dummy receive object and mark the
Scope
and the dummy object
DslMarker
.
Copy code
@DslMarker
annotation class MyDslMarker

@MyDslMarker
class Scope {
    fun method(block: Context.() -> Unit) {}
}

@MyDslMarker
object Context // Dummy object

fun scope(block: Scope.() -> Unit) {}

fun main() {
    scope {
        method {
            method {  } // Compiler error now
        }
    }
}
Any better solution?
s

Sam

07/27/2022, 7:44 AM
Sounds like you need @DslMarker guess you edited your post to include this already
1
j

Jason5lee

07/27/2022, 7:47 AM
Can I do it without adding dummy receiver object?
s

Sam

07/27/2022, 7:48 AM
Ah, I think I see the problem. That’s interesting, I’m not sure
I can’t spot any other way, I think your approach might be the best solution