2

I am playing around with calling external command from Scala. Here is a stripped out example of what I am working on:

import scala.sys.process._

object Testing {
    def main(args: Array[String]) {
        val command = "ls"
        val result = command!
        if (result != 0) {    // <---- illegal start of simple expression
            println("Error")
            return
        }
    }
}

I am getting a compile error: illegal start of simple expression for the line with the if statement. I can fix it with a new line:

val result = command!
                      // Add a line
if (result != 0) { 

My suspicion is that it has something to do with the ! postfix function, but it was my understanding that superfluous lines/whitespaces shouldn't make a difference to the compiler.

Tyler
  • 17,669
  • 10
  • 51
  • 89
  • 2
    This is a common thing, see http://stackoverflow.com/questions/13011204/scalas-postfix-ops Doing what you did is deprecated and you should say `command.!` – Łukasz May 10 '16 at 18:23

1 Answers1

2

You need to explicitly enable postfix expressions:

1) Importing the flag locally: import scala.language.postfixOps

2) or adding the flag to the project itself: scalacOptions += "-language:postfixOps"

The above link in the comment from @Łukasz contains lots of info about this feature. Also, see http://docs.scala-lang.org/style/method-invocation.html in the "Suffix Notation" section for your exact use case.

EDIT: maybe it was not clear enough, but as @Łukasz pointed in comments, importing/enabling postfix expressions doesn't make your code compile. It just avoids the compiler warning. Your code won't compile because the semicolons are optional and the compiler is treating the ! operator as infix, and thus taking elements from the next line for the expressions. This is exactly what the documentation in the link above states with exactly this same example:

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.

names toList
val answer = 42        // will not compile!

This may result in unexpected compile errors at best, and happily compiled faulty code at worst. Although the syntax is used by some DSLs, it should be considered deprecated, and avoided.

ale64bit
  • 6,232
  • 3
  • 24
  • 44
  • 1
    You don't actually need to import this, if you do, you will avoid compiler warnings. It still works exactly the same, so what OP posted wouldn't compile. This is the exact warning message `warning: postfix operator ! should be enabled by making the implicit value scala.language.postfixOps visible. This can be achieved by adding the import clause 'import scala.language.postfixOps' or by setting the compiler option -language:postfixOps. See the Scala docs for value scala.language.postfixOps for a discussion why the feature should be explicitly enabled.` – Łukasz May 10 '16 at 20:24