Narrowing Access with Scope Control
Understand how to apply Kotlin's @DslMarker annotation to narrow access within internal domain-specific languages (DSLs). This lesson guides you through controlling scope in nested lambdas, preventing implicit access to parent receivers. By the end, you will be able to design safer, clearer DSLs with compile-time checking of scope boundaries.
We'll cover the following...
You’ve seen how to create internal DSLs in Kotlin. Unlike external DSLs, internal DSLs have the benefit of riding on a host language, and we don’t have to implement parsers. That removes a lot of effort on our part as DSL designers. However, anything that’s possible in the host language, like property access or calls to arbitrary functions and methods in scope are all permitted within the DSL code. That freedom may be too much at times. Kotlin makes an effort to narrow that access a little with a scope control annotation.
Narrowing access
In spite of the facility Kotlin offers, there’s no way to tell the compiler to reject calls to a top-level function or an access to a variable that’s in lexical scope. But, with a special @DSLMarker annotation, you can tell the compiler to disallow implicit access to the members within the parent receiver of a nested lambda.
We discussed in ...