Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Scala's semicolon inference fail here?

Tags:

scala

On compiling the following code with Scala 2.7.3,

package spoj

object Prime1 {
  def main(args: Array[String]) {
    def isPrime(n: Int) = (n != 1) && (2 to n/2 forall (n % _ != 0))
    val read = new java.util.Scanner(System.in)
    var nTests = read nextInt // [*]
    while(nTests > 0) {
      val (start, end) = (read nextInt, read nextInt)
      start to end filter(isPrime(_)) foreach println
      println
      nTests -= 1
    }
  }
}

I get the following compile time error :

PRIME1.scala:8: error: illegal start of simple expression
    while(nTests > 0) {
    ^
PRIME1.scala:14: error: block must end in result expression, not in definition
  }
  ^
two errors found

When I add a semicolon at the end of the line commented as [*], the program compiles fine. Can anyone please explain why does Scala's semicolon inference fail to work on that particular line?

like image 737
missingfaktor Avatar asked Feb 11 '10 17:02

missingfaktor


People also ask

Can I use semicolons in Kotlin?

In Kotlin, semicolons are optional, and therefore line breaks are significant. The language design assumes Java-style braces, and you may encounter surprising behavior if you try to use a different formatting style.

Is semicolon mandatory in Scala?

In Scala programming, using semicolons is not compulsory.


2 Answers

Is it because scala is assuming that you are using the syntax a foo b (equivalent to a.foo(b)) in your call to readInt. That is, it assumes that the while loop is the argument to readInt (recall that every expression has a type) and hence the last statement is a declaration:

var ntests = read nextInt x

wherex is your while block.

I must say that, as a point of preference, I've now returned to using the usual a.foo(b) syntax over a foo b unless specifically working with a DSL which was designed with that use in mind (like actors' a ! b). It makes things much clearer in general and you don't get bitten by weird stuff like this!

like image 200
oxbow_lakes Avatar answered Oct 19 '22 06:10

oxbow_lakes


Additional comment to the answer by oxbow_lakes...

var ntests = read nextInt()

Should fix things for you as an alternative to the semicolon

like image 33
ColinHowe Avatar answered Oct 19 '22 06:10

ColinHowe