0

I got an error "illegal start of simple expression" in scala while trying to do this:

def test() = {
    val h = "ls"!
    if (h != 0)
        println("error")

}

this is the error

[error]         if (h != 0)
[error] one error found
[error] (compile:compileIncremental) Compilation failed

Can anyone tell me what I did wrong?

风笛手
  • 3
  • 2

2 Answers2

1

Scala compiler is getting confused here because you are calling ! as a postfix operator. It can't figure out which version to use and where to place the implied semicolon. You can either add a semicolon like this:

def test() = {
    val h = "ls"!;
    if (h != 0)
        println("error")
}

or call it as a method:

def test() = {
    val h = "ls".!
    if (h != 0)
        println("error")
}

or add a new line:

def test() = {
    val h = "ls"!

    if (h != 0)
        println("error")
}
yǝsʞǝla
  • 16,272
  • 2
  • 44
  • 65
0

Best practice to use a postfix operator is to use dot . operator. You should invoke it like val h = "ls".!

It makes code less ambiguous as semicolon is optional in Scala and compiler might treat it as an infix notation.

From Scala doc:

This style is unsafe, and should not be used. Since semicolons are optional, the compiler will attempt to treat it as an infix method if it can, potentially taking a term from the next line.

For full reference see this link: Suffix Notation. This post may also be helpful Scala's "postfix ops".

Community
  • 1
  • 1
justAbit
  • 4,226
  • 2
  • 19
  • 34