【问题标题】:Kotlin Builder vs ConstructorKotlin 构建器与构造器
【发布时间】:2017-06-23 06:05:18
【问题描述】:

我对 Kotlin 很陌生,我遇到过这两种表示形式:

Car(name = "CarName")

car { 
  name = "CarName"
}

对于何时应该使用哪一个,是否有任何指导方针? The docs 这个好像不太清楚。

【问题讨论】:

  • 可能更多的是一个“仅风格”的问题,征求意见;但也许 Kotlin 大师可以给出一个很好的基于事实的答案。

标签: kotlin dsl


【解决方案1】:

第二个 sn-p 是如何为您的域构建 DSL 的示例。对于像这样的简单情况,创建 DSL 有点矫枉过正,但是当您的对象变大时,设计 DSL 可能会更简洁。
事实上,使用 DSL 样式创建简单实例甚至可能会让人感到困惑。

例如,the documentation on DSLs 显示以下代码:

fun result(args: Array<String>) =
    html {
        head {
            title {+"XML encoding with Kotlin"}
        }
        body {
            h1 {+"XML encoding with Kotlin"}
            p  {+"this format can be used as an alternative markup to XML"}

            // an element with attributes and text content
            a(href = "http://kotlinlang.org") {+"Kotlin"}

            // mixed content
            p {
                +"This is some"
                b {+"mixed"}
                +"text. For more see the"
                a(href = "http://kotlinlang.org") {+"Kotlin"}
                +"project"
            }
            p {+"some text"}

            // content generated by
            p {
                for (arg in args)
                    +arg
            }
        }
    }

这是您何时可以使用 DSL 的一个很好的示例:该语法使您可以创建一个清晰的模型结构。 Anko 另一个提供了 DSL 来定义 UI。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 2013-08-27
    • 2017-02-12
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多