Control Scope with DslMarker

In Design for Separate Implicit Contexts, we saw that lambdas can have implicit receivers. Lambdas nested within other lambdas may have multiple implicit receivers. Whereas this is a very powerful feature in Kotlin, it may work to our disadvantage when our goal is to restrict the functions that may be called from within a scope. Kotlin provides a way to limit the scope within a DSL to a single implicit receiver, using a special annotation—DslMarker.

Let’s revisit the design of the DSL from Design for Separate Implicit Contexts, and discuss the issue we’ll run into. Then we’ll see how we can resolve it—with the help of Kotlin, of course.

Suppose the user of the builder DSL writes something like this:

 build {

Get Programming DSLs in Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.