blue-sky
blue-sky

Reputation: 53806

Method evaluation not behaving as expected

Below code calculates the total a fibonacci sequence to a particular number.

But a StackOverFlow exception is being thrown. Why is this exception being thrown as I am checking for 0 within the function ?

object fibonacci extends Application {

def fibonacci(i : Int) : Int = {
    println(i)
    if(i == 0) 0
    if(i == 1) 1
    fibonacci(i - 1) + fibonacci(i - 2)
}

fibonacci(3)

}

Error :

scala> fibonacci(3)
3
2
1
0
-1
-2
-3
-4
-5
-6
-7
-8
-9
.......


scala> fibonacci(3)
java.lang.StackOverflowError
        at .fibonacci(<console>:10)
        at .fibonacci(<console>:10)
        at .fibonacci(<console>:10)
        at .fibonacci(<console>:10)

Upvotes: 1

Views: 69

Answers (2)

Shadowlands
Shadowlands

Reputation: 15074

Scala will automatically evaluate the return value of a function to be the value of the last statement calculated (this is the reason you don't need the return keyword).

Without elses, your two if statements are stand-alone statements, but not the last statement in the function. They resolve to a value, but this value is not assigned to anything and so is thrown away and the function continues processing statements.

Putting elses in (as per @Marth's solution) ensures that you end the function with one single statement consisting of a single if-else chain. This whole statement (and hence, the function) evaluates to the result of whichever branch of the chain is selected and executed.

You can also acheive the effect you want using a match (which is also treated as one single statement):

def fibonacci(i : Int) : Int = {
    println(i)
    i match {
        case 0 => 0
        case 1 => 1
        case _ => fibonacci(i - 1) + fibonacci(i - 2)
    }
}

Upvotes: 2

Marth
Marth

Reputation: 24802

def fibonacci(i : Int) : Int = {
    println(i)
    if (i == 0) 0
    else if (i == 1) 1
    else fibonacci(i - 1) + fibonacci(i - 2)
}

Without those else you're not stopping when you reach 0 or 1.

Upvotes: 3

Related Questions