kotlin - 是否可以在 Kotlin DSL 中完全避免函数名称?

标签 kotlin dsl receiver

Kotlin DSL例如,他们使用 plus 符号来实现原始内容插入:

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

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

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

Kotlin 的 future 版本是否有这样做的计划?

除了 Kotlin 之外,其他语言中有这样的东西吗?

最佳答案

我可以想到两种解决你的问题的方法:

  1. 让带有接收者的 lambda 返回一个 String:

    fun title(init: Title.() -> String) {
        val t = Title().apply {
            children.add(TextElement(init()))
        }
        children.add(t)
    }
    

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

  2. 创建另一个直接接受 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")
    }
    

关于kotlin - 是否可以在 Kotlin DSL 中完全避免函数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49580907/

相关文章:

android - 注销接收器是必要的吗?

objective-c - 如何定义和发送将 UIBarButtonItems 动态添加到 UIToolbar 的方法\消息?

java - 用于发现蓝牙设备不工作的广播接收器

Android Jetpack Compose (Composable) 从 Coroutine 获取 String 资源

java - Servlet/Undertow - 访问 HttpServletRequest 和 HttpServletResponse

java - 我如何获取父工具栏名称

c# - DSL/流畅接口(interface)的意义何在

groovy - 在 groovy shell 中使用 groovy 类别

java - build.gradle - 找不到参数的方法 copyDeps()

Android Studio - Kotlin 测试抛出 - 找不到类 - 空测试套件