Search code examples
scalaunary-operator

What are the differences between these two Scala code segments regarding postfix toString method?


I am learning postfix unary operators in Scala. The following can not compile:

val result = 43 toString    
println(result)

However if I add one empty line inbetween the two lines, the code compile and produces right output:

val result = 43 toString

println(result)

What is the difference between these two segments? BTW, I did not add "import scala.language.postfixOps".


Solution

  • Perhaps the issue is clearer if we use some other operator instead of toString.

    // This parses as `List(1,2,3,4) ++ List(4,5,6)` 
    List(1,2,3,4) ++
    List(4,5,6)
    

    Basically, in order to make the above work, while also allowing things like foo ? (a postfix operator), Scala needs to know when it is OK to stop expecting a second argument (and accept that the expression is a postfix operator).

    Its solution is give up on finding a second argument if there is an interceding new line.