When I comment out one line with // in this code, it doesn't work as expected.
open class Tag(val name: String) {
private val children = mutableListOf<Tag>()
protected fun <T : Tag> doInit(child: T, init: T.() -> Unit) {
println("$child passed to doInit.")
init(child)
children.add(child)
println("$child added")
}
override fun toString(): String {
println("toString called and ..now " +
"we have: <$name>${children.toString()}</$name>\"")
return "<$name>${children.toString()}</$name>"
}
}
fun table(init: TABLE.() -> Unit): TABLE {
println("table called")
return TABLE().apply(init)
}
class TABLE : Tag("table") {
fun tr(init: TR.() -> Unit) {
println("tr called")
doInit(TR(), init);
println("after tr's doInit called")
}
}
class TR : Tag("tr") {
fun td(init: TD.() -> Unit) {
println("td called")
doInit(TD(), init);
println("after td's doInit called")
}
}
class TD : Tag("td")
fun createTable() =
table {
tr {
td {
}
}
}
Even when I comment out init(child),
fun createTable1() = table{tr{}}
works as expected. It calls doInit, and produces:<table><tr></tr></table>
But
fun createTable2() = table{tr{td{}}}
doesn't call doInit on td. It produces:<table><tr></tr></table>
and not:
<table><tr><td></td></tr></table>
Thank you very much for reading.