Kotlin DSL for creating json objects (without creating garbage) : <p>I am trying to create a DSL for creating JSONObjects. Here is a builder class and a sample usage:</p>

<pre><code>import org.json.JSONObject

fun json(build: JsonObjectBuilder.() -&gt; Unit): JSONObject {
    val builder = JsonObjectBuilder()
    builder.build()
    return builder.json
}

class JsonObjectBuilder {
    val json = JSONObject()

    infix fun &lt;T&gt; String.To(value: T) {
        json.put(this, value)
    }
}

fun main(args: Array&lt;String&gt;) {
    val jsonObject =
            json {
                "name" To "ilkin"
                "age" To 37
                "male" To true
                "contact" To json {
                    "city" To "istanbul"
                    "email" To "xxx@yyy.com"
                }
            }
    println(jsonObject)
}
</code></pre>

<p>The output of the above code is :</p>

<pre><code>{"contact":{"city":"istanbul","email":"xxx@yyy.com"},"name":"ilkin","age":37,"male":true}
</code></pre>

<p>It works as expected. But it creates an additional JsonObjectBuilder instance every time it creates a json object. Is it possible to write a DSL for creating json objects without extra garbage?</p>
