LastExceed
11/09/2021, 5:44 PMfun main() {
val root = Thing(null, 0).apply {
addChild(1) {
addChild(2)
addChild(3) {
addChild(4)
}
}
addChild(5)
}
root.printTree()
}
abstract class Nestable(
val parent: Nestable?
) {
val children = mutableListOf<Nestable>()
}
class Thing(
parent: Thing?,
val number: Int
) : Nestable(parent) {
init {
parent?.children?.add(this)
}
fun addChild(
number: Int,
block: Nestable.() -> Unit = {}
) = Thing(this, number).run(block)
fun printTree(indentation: Int = 0) {
println(" ".repeat(indentation) + number)
children.forEach {
(it as? Thing)?.printTree(indentation + 1)
}
}
}
expected output:
0
1
2
3
4
5
actual output:
0
1
2
3
4
5
find the bug >:)Paul Griffith
11/09/2021, 6:07 PMaddChild
accepts a trailing lambda with Nestable
, instead of Thing
, as the context receiver, so you get the outermost Thing
from apply
as the receiver instead of the innermost...LastExceed
11/09/2021, 6:08 PMkqr
11/09/2021, 6:09 PMPaul Griffith
11/09/2021, 6:09 PMLastExceed
11/09/2021, 6:11 PMNestable
has an addChild
function so it takes the nearest receiver, whereas before it had to go all the way out to the root to find a receiver of type Thing
Joffrey
11/09/2021, 10:59 PM@
)