This is NOT tailrec `tailrec fun TreeNode.findMin(...
# announcements
g
This is NOT tailrec
tailrec fun TreeNode.findMin(): TreeNode = left?.findMin() ?: this
But this is:
tailrec fun TreeNode.findMin(): TreeNode = if (left == null) this else left!!.findMin()
I am missing the concise syntax, why can’t the compiler smartly make the first one
tailrec
c
I’m guessing because the compiler still needs to do a null-check (with the elvis operator) after calling
.findMin()
in the first example, because nulls get passed all the way through the call chain. In the second example, the null-check there is before the call to
.findMin()
, so
findMin()
actually is the last call being made
👆 1
💯 1
p
from looking at your first code snippet, you don’t call recursively as the last statement, hence, as much as I understand it, it is not a tailrec function https://kotlinlang.org/docs/reference/functions.html#tail-recursive-functions
2
1