How can I get rid of `!!` in below code without ge...
# getting-started
m
How can I get rid of
!!
in below code without getting compilation errors and without getting ugly code? Edit: And without recursion
Copy code
class Node(val child: Node?)

fun Node.getLeaf(): Node {
    var candidate: Node = this
    while (candidate.child != null) {
        candidate = candidate.child!!
    }
    return candidate
}
t
tail recursion.
Copy code
fun Node.getLeaf() : Node = findLeaf(this)

tailrec fun findLeaf(candidate: Node) {
  val child = candidate.child
  if(child == null) return candidate
  return findLeaf(child)
}
❤️ 1
👏 1
s
Copy code
while (true) {
        candidate = candidate.child ?: break
    }
☝️ 2
🤩 2
👍 2
m
Wow that is truly beatiful code 🤩 Thanks a lot!
w
Copy code
tailrec fun Node.getLeaf(): Node = when (child) {
    null -> this
    else -> child.getLeaf()
}
My 2 cents 🙂
Copy code
@Test
    fun asas() {
        val nodes =
            Node(
                0,
                Node(
                    1,
                    Node(2, null)
                )
            )
        assertEquals(Node(2, null), nodes.getLeaf())
    }
1
👍 3
t
cool did not think to use pattern matching (if you can call it so), that is still something I have to get used to coming from java (I guess java 12 would help). awesome!