Reputation: 5659
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?
Upvotes: 2
Views: 2337
Reputation: 4965
Your guess is correct. The method must return a Double, yours would return Unit if non of the "if.." cases match. Actually, when you paste the second definition into the repl, you should get
<console>:11: error: type mismatch;
found : Unit
required: Double
Upvotes: 0
Reputation: 43310
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.
Upvotes: 7
Reputation: 30736
No - In general, an if
expression does not require an else
clause.
Examples:
if (true) println("a")
// prints "a"
if (false) println("a") else if (true) println("b")
// prints "b"
As Nikita Volkov's answer says, though, it is necessary if you need the expression to have some type other than Unit
.
Upvotes: 3