I just start learning scala. I got an error "illegal start of simple expression" in eclipse while trying to implement a recursive function:
def foo(total: Int, nums: List[Int]):
if(total % nums.sorted.head != 0)
0
else
recur(total, nums.sorted.reverse, 0)
def recur(total: Int, nums: List[Int], index: Int): Int =
var sum = 0 // ***** This line complained "illegal start of simple expression"
// ... other codes unrelated to the question. A return value is included.
Can anyone tell me what I did wrong about defining a variable inside a (recursive) function? I did a search online but can't one explains this error.
The indentation seems to imply that recur
is inside count
, but since you did not place {
and }
surrounding it, count
is just the if-else, and recur
is just the var
(which is illegal -- you have to return something).
A variable declaration (var
) doesn't return a value, so you need to return a value somehow, here's how the code could look like:
object Main {
def foo(total: Int, coins: List[Int]): Int = {
if (total % coins.sorted.head != 0)
0
else
recur(total, coins.sorted.reverse, 0)
def recur(total: Int, coins: List[Int], index: Int): Int = {
var sum = 0
sum
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With