The method in the class below assumes that y
is positive:
class Calculator {
def addPos(x: Int, y: Int): Int = {
if (y == 0) x
else {
val temp: Int = x + 1
if (temp < x) throw new OverflowException
else addPos(temp, y - 1)
}
}
}
It is tail recursive and adds one to x
from y
in each recursion until y
is 0. It also throws when be exceed Int.MaxValue
. I know that there is a far simpler implementation of this function that doesn't need recursion, BUT, I want to find out why this method causes a StackOverflowError when I do:
val newCalc = new Calculator
println(newCalc.addPos(0, Int.MaxValue))
I thought that since it's tail recursive, the method could not cause an SOError.