Do if else statements in Scala always require an else?

scala

Solution

In Java "if-else" is a statement. In Scala it is an expression (think of Java's ternary `?:`), meaning that it always produces some value. As mentioned by som-snytt in comments, in case of a missing `else` block the compiler supplies `else ()`, which is of type `Unit`, which obviously conflicts with the expected type `Double` in your example.

Some valid examples of missing `else` are provided in Chris's answer.

Problem

I have the following function which works fine: ``` def power(x: Double, n: Int) : Double = { if (n > 0 && n % 2 == 0) power(x, n/2) * power(x, n/2) else if (n > 0 && n % 2 == 1) x * power(x, n-1) else if (n < 0) 1 / power(x, -n) else 1 } ``` If I change it to be: ``` def power(x: Double, n: Int) : Double = { if (n > 0 && n % 2 == 0) power(x, n/2) * power(x, n/2) else if (n > 0 && n % 2 == 1) x * power(x, n-1) else if (n < 0) 1 / power(x, -n) else if (n==0 ) 1 } ``` I.e. change the final `else` statement to be an `else if`, then I get the following error trying to call the function: ``` > <console>:8: error: not found: value power power(2, 1) ^ ``` I'm guessing this is because there is a possible return type of Unit because the value of `n` could meet none of the conditions?

Original source

Related problems