在使用Ktor的HTML构建器时,如何将部分代码提取到Kotlin的局部变量中?

我想了解Kotlin / Ktor中的HTML生成器。 这里的示例使用HTML生成器来生成结果:

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

我正在尝试将这个身体提取到像这样的变量中:

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

现在我得到以下编译错误:

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

当我添加第一个(可选)参数它再次工作: call.respondHtml(HttpStatusCode.OK, block)

为什么它不工作,当我只是试图提取身体变量?

我认为编译器不喜欢默认参数后面有一个强制的,除非它是大括号外的lambda。

尝试命名它:

 call.respondHtml(block = block) 

顺便说一句,如果你想要的是提取逻辑,我会推荐使用函数。 举个例子:

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

这样,你甚至可以添加参数到你的HTML块,创建一个自定义组件。