My code:
def power(x: Double, n: Int): Double = {
if (n % 2 == 0 && n > 0) power(power(x, n/2), 2)
else if (n % 2 == 1 && n > 0) x * power(x, n - 1)
else if (n == 0) 1
else if (n < 0) 1 / power(x, -n)
}
println(power(2, 2))
Terminal:
$ scala ch2ex10.scala
/scala/impatient/ch2ex10.scala:5: error: type mismatch;
found : Unit
required: Double
else if (n < 0) 1 / power(x, -n)
Where is this Unit coming from?
Thanks!
It comes from the last “else if” in the block.
It doesn’t look like all possibilities are exhausted. If there is no other possibility left (which happens to be the case here), just write
if another possibility would be open, you would need to write
and fill out the dots. Else the compiler assumes
for you.