Last active
December 13, 2022 06:23
Star
You must be signed in to star a gist
Kotlin DSL Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() { | |
val root = NodeBuilder { | |
"Ali"{ | |
"Bob"{ | |
"Candy"() | |
"Dave"() | |
} | |
"Egg"{ | |
"Fold"() | |
} | |
} | |
} | |
print(root) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class Node( | |
val name: String, | |
val children: MutableList<Node> = mutableListOf() | |
) { | |
override fun toString() = "$name${if (children.isNotEmpty()) children.toString() else ""}" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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