Is it possible to hide variables from lambda closure?

I am trying to create a safe groovy line builder style in Kotlin, as described here . The problem is the visibility of lambdas in nested lambdas. Here is a simple example.

html { head(id = "head1") body() { head(id = "head2") } } 

The receiver of a nested lambda is a Body that does not have a head method. However, this code is compiled and printed as follows:

 <html> <head id="head1"></head> <head id="head2"></head> <body></body> </html> 

It is expected, but is there a way to get a compilation error on the inner head?

+5
source share
2 answers

As of Kotlin 1.0, this is not possible. There is an open function request for this function .

+4
source

This is possible since Kotlin 1.1, thanks to the introduction of the @DslMarker annotation .

Here is an example of how to use it:

 @DslMarker annotation class MyHtmlDsl @MyHtmlDsl class HeadBuilder @MyHtmlDsl class BodyBuilder @MyHtmlDsl class HtmlBuilder { fun head(setup: HeadBuilder.() -> Unit) {} fun body(setup: BodyBuilder.() -> Unit) {} } fun html(setup: HtmlBuilder.() -> Unit) {} fun main(args: Array<String>) { html { head {} body { head { } // fun head(...) can't be called in this context by implicit receiver } } } 

See also the documentation for the above message.

0
source

All Articles