How do I extract parts of code into local variables in Kotlin when using Ktor's HTML builder?

Viewed 296

I am trying to understand the HTML builder in Kotlin / Ktor. The example here uses the HTML builder to build the result:

call.respondHtml {
    head {
        title { +"HTML Application" }
    }
    body {
        h1 { +"Sample application with HTML builders" }
        widget {
            +"Widgets are just functions"
        }
    }
}

I am trying to extract the body into a variable like this:

val block: HTML.() -> Unit = {
    head {
        title { +"HTML Application" }
    }
    body {
        h1 { +"Sample application with HTML builders" }
    }
}
call.respondHtml(block)

Now I get the following compile error:

Error:(37, 22) Kotlin: None of the following functions can be called with the arguments supplied: 
public suspend fun ApplicationCall.respondHtml(status: HttpStatusCode = ..., versions: List<Version> = ..., cacheControl: CacheControl? = ..., block: HTML.() -> Unit): Unit defined in org.jetbrains.ktor.html
public suspend fun ApplicationCall.respondHtml(status: HttpStatusCode = ..., block: HTML.() -> Unit): Unit defined in org.jetbrains.ktor.html

When I add the first (optional) argument it works again: call.respondHtml(HttpStatusCode.OK, block).

Why does it not work, when I simply try to extract the body into a variable?

2 Answers
Related