class TreeNode() {
var child: TreeNode? = null
}
fun test(root: TreeNode?) {
run {
var node: TreeNode? = root
while (node != null) {
node = node.child
}
}
fun innerMethod() {
var node: TreeNode? = root
while (node != null) {
// Why compile error here?
node = node.child // Smart cast to 'TreeNode' is impossible, because 'node' is a local variable that is captured by a changing closure
}
}
}
fun main() {
test(TreeNode())
}
I fix the error like below, but still don’t understand the problem.
fun innerMethod() {
var node1: TreeNode? = root
while (node1 != null) {
node1 = node1.child
}
}
As far as I understand, shadowing is when child scope hides the parent scope.
But in this case, they are in 2 unrelated scopes. Why the later scope can be a shadow of previous scope in this case?
Do I misunderstand something?