Skip to content

Instantly share code, notes, and snippets.

@dyguests
Last active December 13, 2022 06:23
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dyguests/5e3b615cce87071fde846882268f8220 to your computer and use it in GitHub Desktop.
Kotlin DSL Tree
fun main() {
val root = NodeBuilder {
"Ali"{
"Bob"{
"Candy"()
"Dave"()
}
"Egg"{
"Fold"()
}
}
}
print(root)
}
data class Node(
val name: String,
val children: MutableList<Node> = mutableListOf()
) {
override fun toString() = "$name${if (children.isNotEmpty()) children.toString() else ""}"
}
class NodeBuilder {
private var parent: Node? = null
private lateinit var node: Node
operator fun String.invoke(block: (NodeBuilder.() -> Node)? = null): Node {
node = Node(this)
parent?.children?.add(node)
if (block != null) {
val nodeBuilder = NodeBuilder()
nodeBuilder.parent = this@NodeBuilder.node
nodeBuilder.block()
}
return node
}
companion object {
operator fun invoke(block: NodeBuilder.() -> Node): Node {
return NodeBuilder().block()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment