Illegal start of a simple expression in Scala

I'm just starting to learn scala. I got the error “illegally starting a simple expression” in eclipse when 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 someone tell me what I did wrong in defining a variable inside a (recursive) function? I did a search on the Internet but cannot explain this error.

+6
source share
3 answers

Declaring a variable ( var ) does not return a value, so you need to somehow return the value, what the code looks 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 } } } 
+6
source

Indentation means that recur is inside count , but since you did not place { and } around it, count is just if-else, and recur is just var (which is illegal - you need to return something).

0
source

I had a similar problem. Found example 8.1 in a book that looked like this:

 object LongLines { def processFile(filename: String, width: Int) **{** val source = Source.fromFile(filename) for (line <- source.getLines) processLine(filename, width, line) **}** 

Note: "def processFile (file name: String, width: Int) {" and end "}"

I surrounded the body of 'method' {} and scala compiled it without error messages.

0
source

All Articles