May 13, 2009

Parser surprise

1.toString works fine

-1.toString saz " error: ';' expected but '.' found."

need to use (-1).toString

5 comments:

Daniel said...

- in -1 is not part of the (numeric) literal, but an operator.

There is another example of a surprising situation that results from Scala's "everything is an operator" in Programming in Scala, which I read just yesterday as I revised a few chapters, but I couldn't find it. I think chapter 5.

Unknown said...

Strangely, though, "- 1 . toString" isn't parsed as either "(- 1) . toString", which compiles, or "- (1 . toString)", which can be made to compile by defining how unary minus acts on strings.

Kevin said...

Leaving out the dot works:

scala> -1 toString
res7: java.lang.String = -1

Derek Mahar said...

I find this surprising, too. I would have expected the unary "-" (minus) operator to have higher precedence than the "." (member access) operator.

Daniel said...

I found the example from the book. RichInt's abs on page 208.

As for ".", it has precedence over any operator. After all, if you wrote "line.length - word.length", you'd certainly expect length to be applied first.

It's important to realize, though, that "." is NOT an operator in Scala.

In the absence of ".", normal precedence rules applies -- that is, "-" has precedence over all letters.