Extension functions

In the previous example, the html function was called and its internal implementation was left to provide an initial instance of the HTML class that we can use with the passed init function. This is convenient when we're beginning a new HTML construction from scratch.

In some cases, you may want to leverage your DSL with an existing object. For those cases, you could use an extension function to provide an alternative entry point to your declarative DSL. The following code shows this:

val result = html {
...
}

result.html {
body {
p {+"add on to existing HTML"}
}
}

To enable this extension of an existing HTML object, we can create a simple extension function like the following:

fun HTML.html(init: HTML.() -> Unit): HTML {
init()
return this
}

This takes the same type of receiver argument but relies on the implicit HTML receiver of the extension function for configuration, thereby allowing us to add to what is already configured in the existing HTML.