Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Builder vs Constructor

Tags:

kotlin

dsl

I'm pretty new to Kotlin, and I've come across both of these representations:

Car(name = "CarName")

and

car { 
  name = "CarName"
}

Is there any guidelines about when which one should be used? The docs don't seem to be too clear on this.

like image 942
Bernd Avatar asked Jun 23 '17 06:06

Bernd


1 Answers

The second snippet is an example of how you could build a DSL for your domain. For simple cases like this, it is a bit overkill to create a DSL, but when your objects get larger it might be cleaner to design a DSL.
In fact, using the DSL style to create simple instances might even be confusing.

For example, the documentation on DSLs shows the following code:

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
            }
        }
    }

This is an excellent example of when you could use a DSL: The syntax enables a clean structure of how you create your models. Anko for another provides a DSL to defines UI's.

like image 162
nhaarman Avatar answered Oct 14 '22 08:10

nhaarman