ChuanRocks
ChuanRocks

Reputation: 1528

Illegal start of simple expression in 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.

Upvotes: 17

Views: 66972

Answers (4)

Christian Dicker
Christian Dicker

Reputation: 11

I had a similar problem where I was doing something like

nums.map(num =>
  val anotherNum = num + 1
  anotherNum
)

and the way to fix it was to add curly braces:

nums.map { num =>
  val anotherNum = num + 1
  anotherNum
}

I thought these expressions were equivalent in Scala, but I guess I was wrong.

Upvotes: 1

Vito
Vito

Reputation: 9

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

object LongLines {

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

Note: the "def processFile(filename: String, width: Int) {" and ending "}"

I surrounded the 'method' body with {} and scala compiled it with no error messages.

Upvotes: 0

Maur&#237;cio Linhares
Maur&#237;cio Linhares

Reputation: 40333

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
    }

  }


}

Upvotes: 13

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297295

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

Upvotes: 2

Related Questions