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

时间:2017-08-05 13:28:34

标签: kotlin extension-methods dsl ktor

我正在尝试了解Kotlin / Ktor中的HTML构建器。 example here使用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)

为什么它不起作用,当我只是尝试将主体提取为变量?

2 个答案:

答案 0 :(得分:3)

我认为编译器不喜欢在默认参数之后使用强制,除非它是大括号之外的lambda。

尝试命名:

woocommerce_available_payment_gateways

答案 1 :(得分:3)

顺便说一句,如果您想要提取逻辑,我建议使用函数。以你的例子:

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

call.respondHtml {
    headAndBody()
}

这样你甚至可以在你的html块中添加参数,从而创建一个自定义组件。