Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal start of simple expression in Scala

Tags:

syntax

scala

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.

like image 889
ChuanRocks Avatar asked Apr 12 '13 03:04

ChuanRocks


2 Answers

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).

like image 123
Daniel C. Sobral Avatar answered Oct 16 '22 09:10

Daniel C. Sobral


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
    }

  }


}
like image 42
Maurício Linhares Avatar answered Oct 16 '22 09:10

Maurício Linhares