Why does this Scala recursion
def foo(id:Int): Int = {
if (id == 0) { return id } else { foo(id - 1) }
}
foo(2)
returns 0, while this Python recursion returns None?
def foo(id):
if id == 0:
return id
else:
foo(id - 1)
foo(2)
In which way do Python and Scala handle recursion and manage nested activation records?
In Scala, any block is evaluated to the value of it's last statement. For example, you can write:
Here,
myValwould evaluated to9.Similarly, your
elseblock evaluates to the value returned fromfoo(id - 1)(even though there's no explicitreturnkeyword), and therefore the value of the entire method body would evaluate to that value as long as theelseblock is reached (the entireifstatement would be evaluated to the result offoo(id - 1), and since thatifis the last (and only) statement in the method body - that would be the method's return value).You can drop the first
returnkeyword as well:In Python, that's simply not the case; Only
returnstatements signify the method's return value. If you return nothing,Noneis returned.