7

In Java, < has higher priority than ==. In Scala it's vice versa. I wonder why Scala people chose that way? Other binary operator precedences align with Java (exept bitwise ops, but it's understandable why they didn't give special precedences for those).

UPDATE: It was actually a mistake in the language spec, '<' has actually higher priority than '==' in Scala.

Aivar
  • 6,814
  • 5
  • 46
  • 78

1 Answers1

14

It's not inversed in Scala. Try this:

val what = 5 == 8 < 4

I get a compile-time warning: comparing values of types Boolean and Int using `==' will always yield false; so obviously the compiler has translated this to 5 == (8 < 4), just like in Java.

You can try this, too:

class Foo {
  def ===(o: Foo) = { println("==="); this }
  def <<<(o: Foo) = { println("<<<"); this }
  def >>>(o: Foo) = { println(">>>"); this }
}

def foo = new Foo

Then calling foo === foo <<< foo >>> foo prints this:

<<<
>>>
===

Which means it was parsed as (foo === ((foo <<< foo) >>> foo))

Can you provide an example where the precedence is reversed?

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
  • 1
    Then maybe it's a typo?… I wouldn't dare to contradict the Reference, but from these two tests, methods beginning with `<` have higher precedence than methods beginning with `=` when used in infix notation (on Scala 2.8.1). – Jean-Philippe Pellet Aug 11 '11 at 15:01
  • Thanks for the extended example -- it really seems there is typo in the reference. I was comparing operator precedences in different languages, that's why I noticed it. – Aivar Aug 11 '11 at 17:31
  • The documentation was still wrong in 2.8, where it claimed that infix operators starting with '=' are higher priority than those starting with '<', but it's not true. '5 < 4 == 5 < 4' works as expected, but 'true & false == true & false' is not the same as '(true & false) == (true & false)', even though '&' and '<' are both lower than '='. – Wayne Oct 15 '13 at 22:29
  • Fixed at 2.11 (or earlier) - http://www.scala-lang.org/files/archive/spec/2.11/06-expressions.html#prefix-operations – Lior Chaga Jun 22 '15 at 15:17