title: Kotlin type safe builder DSLs, safety for the outermost function
body: <p>I'm going to use the <a href="https://kotlinlang.org/docs/reference/type-safe-builders.html#full-definition-of-the-comexamplehtml-package" rel="noreferrer">official example</a> from the documentation that implements a DSL for some HTML creation.</p>
  
  <p>Since Kotlin 1.1, the <code>@DslMarker</code> annotation allows us to restrict the scope of the functions in our classes, like the example does with the <code>@HtmlTagMarker</code> annotation. This gives us an error when trying to write incorrectly structured code like this:</p>
  
  <pre><code>html {
      body { 
          body { // this in an error, as it's a function call on the outside Html element
          }
      }
  }
  </code></pre>
  
  <p>However, this doesn't prevent nesting the outermost function, which is the entry point to the DSL. For example, with the example as it is now, this can be written down without problems:</p>
  
  <pre><code>html {
      html {
      }
  }
  </code></pre>
  
  <p>Is there any way to make a DSL safer in this regard?</p>