首页 文章

是否有可能在Kotlin DSL中完全避免使用功能名称?

提问于
浏览
3

Kotlin DSL示例中,他们使用 plus 标志来实现原始内容插入:

html {
    head {
        title {+"XML encoding with Kotlin"}
    }
    // ...
}

是否可以在接收器中定义“无名”功能以便能够写入

html {
    head {
        title {"XML encoding with Kotlin"}
    }
    // ...
}

在未来的Kotlin版本中是否有任何计划?

除了Kotlin,语言中还有这样的东西吗?

1 回答

  • 5

    我可以想到两个问题的解决方案:

    • 使接收器的lambda返回 String
    fun title(init: Title.() -> String) {
        val t = Title().apply {
            children.add(TextElement(init()))
        }
        children.add(t)
    }
    

    您现在可以按照OP中的建议调用 title . 实际上这似乎是在这个特定情况下的开销,我建议如下 .

    • 创建另一个直接接收 Stringtitle 方法:
    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")
    }
    

相关问题