在Kotlin DSL例如,他们使用 plus
符号来实现原始内容插入:
html {
head {
title {+"XML encoding with Kotlin"}
}
// ...
}
是否可以在接收器中定义“无名”函数以便能够写入
html {
head {
title {"XML encoding with Kotlin"}
}
// ...
}
Kotlin 的 future 版本是否有这样做的计划?
除了 Kotlin 之外,其他语言中有这样的东西吗?
最佳答案
我可以想到两种解决你的问题的方法:
让带有接收者的 lambda 返回一个
String
:fun title(init: Title.() -> String) { val t = Title().apply { children.add(TextElement(init())) } children.add(t) }
您现在可以按照 OP 中的建议调用
title
。实际上,在这种特定情况下这似乎是开销,我建议如下。创建另一个直接接受
String
的title
方法: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) } }
这样使用:
head { title("XML encoding with Kotlin") }
关于kotlin - 是否可以在 Kotlin DSL 中完全避免函数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49580907/