Dim*_*ims 3 dsl receiver kotlin
在Kotlin DSL示例中,他们使用plus符号来实现原始内容插入:
html {
head {
title {+"XML encoding with Kotlin"}
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
是否可以在接收器中定义"无名"功能以便能够写入
html {
head {
title {"XML encoding with Kotlin"}
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
在未来的Kotlin版本中是否有任何计划?
除了Kotlin,语言中还有这样的东西吗?
我可以想到两个问题的解决方案:
使接收器使lambda返回String:
fun title(init: Title.() -> String) {
val t = Title().apply {
children.add(TextElement(init()))
}
children.add(t)
}
Run Code Online (Sandbox Code Playgroud)
您现在可以title按OP中的建议调用.实际上这似乎是在这个特定情况下的开销,我建议如下.
创建另一个直接title采用的方法String:
class Head : TagWithText("head") {
fun title(init: Title.() -> Unit) = initTag(Title(), init)
fun title(text: String) {
val t = Title().apply {
children.add(TextElement(text))
}
children.add(t)
}
}
Run Code Online (Sandbox Code Playgroud)
像这样使用:
head {
title("XML encoding with Kotlin")
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |