Reputation: 400
I am practicing scala's simple recursive function. This is from a book
def calculatePower(x:Int, y:Int): Long = {
if (x>=1)
x*calculatePower(x,y-1)
else 1
}
calculatePower(2,2)
Upvotes: 0
Views: 36
Reputation: 12783
Your method stack overflows because it doesn't terminate and the stack frames accumulates until there is no more room.
if (x>=1) x*calculatePower(x,y-1)
You test if x
is greater or equal to 1 but in the recursive call you only decrement y
!
Upvotes: 0
Reputation: 6182
You are checking x
but you are decrementing y
. That means your base-case will never be reached.
Upvotes: 2