Asking for help understanding builders

I would like to create a builder for a custom data type and I'm trying to understand the example builders already posted in various blogs.

I’ll paste the code from one example I saw in another discussion thread in this forum.

I don’t understand the call tag.init()

I see that (tag: T …) means there is an argument “tag” of type T and that the init() function is called on it, but I’m not sure if that is implictly calling a constructor or something else.

Thanks for any guidance!


package org.netkernelroc.util.hds

import java.util.ArrayList

abstract class Factory<T> {
  abstract fun create(): T

abstract class J

abstract class JObject: J() {
  val children = ArrayList<J>()

  protected fun initTag<T: J>(tag: T, init: T.() -> Unit): T {
  return tag

class JSON: JObject() {
  fun obj(init: JObject.() -> Unit) = initTag(JSON(), init)

fun json(init: JSON.() -> Unit): JSON {
  val json = JSON()
  return json

Maybe better to look this example, it seems more clear. Also there is some docs.

init:T.() is extension function for tag variable. So in json { …body… } you can access this tag via this, that can be omitted.

Here is another example of a JSON DSL I wrote, which you might find useful.