Between execution of left != null and queue.add(left) another thread could have changed the value of left to null.
To work around this you have several options. Here are some:
-
Use a local variable with smart cast:
val node = left if (node != null) { queue.add(node) } -
Use a safe call such as one of the following:
left?.let { node -> queue.add(node) } left?.let { queue.add(it) } left?.let(queue::add) -
Use the Elvis operator with
returnto return early from the enclosing function:queue.add(left ?: return)Note that
breakandcontinuecan be used similarly for checks within loops.