why it required me to add `!!` in my `while` loop,...
# announcements
c
why it required me to add
!!
in my
while
loop, while I already check node.right will never be null
s
val
is needed for smart-casting to work
s
Because the compiler cannot guarantee that another thread never changes the value of
node.right
right after the null check
👍 1
s
👍 1
c
is there another way to write a better code here?
s
Copy code
while (node?.right != null) {
        node = node?.right
    }
^^^ only if you are sure that there are no race conditions, ie no other threads can suddenly and unexpectedly change the
.right
of the node(s).
d
Copy code
while (true) {
    node = node.right ?: break
}
😅 1
s
you probably could make this a
tailrec fun
d
But I dont think it would be beneficial
s
I mean, it would make the node argument immutable, slightly more elegant than caching in a val or anything like that
s
you could put the value into a local variable so that’s insured that no other thread can change it
Copy code
private fun predecessor(): Int {
        var node = this.left!!
        var rightNode = node.right
        while (rightNode != null) {
            rightNode = rightNode.right
        }
        return rightNode?.data ?: node.data
    }
a tailrec solution
Copy code
private fun predecessor(): Int {
    tailrec fun getRightMostData(node: Node): Int {
        val rightNode = node.right
        return if(rightNode==null) node.data
               else getRightMostData(rightNode) 
	}
    return getRightMostData(this.left!!)
}
👍 1