问题描述
在 Java 中,<具有比 == 更高的优先级.在 Scala 中,反之亦然.我想知道为什么 Scala 人会选择这种方式?其他二元运算符的优先级与 Java 一致(按位运算除外,但可以理解为什么他们没有为它们提供特殊的优先级).
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).
更新:这实际上是语言规范中的一个错误,'<'实际上比 Scala 中的 '==' 具有更高的优先级.
UPDATE: It was actually a mistake in the language spec, '<' has actually higher priority than '==' in Scala.
推荐答案
它在 Scala 中没有反转.试试这个:
It's not inversed in Scala. Try this:
val what = 5 == 8 < 4
我收到一个编译时警告:使用 `==' 比较 Boolean 和 Int 类型的值总是会产生 false
;所以很明显编译器已经把它翻译成 5 == (8 < 4)
,就像在 Java 中一样.
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.
你也可以试试这个:
class Foo {
def ===(o: Foo) = { println("==="); this }
def <<<(o: Foo) = { println("<<<"); this }
def >>>(o: Foo) = { println(">>>"); this }
}
def foo = new Foo
然后调用foo === foo <<<foo >>>foo
打印:
<<<
>>>
===
这意味着它被解析为 (foo === ((foo <<< foo) >>> foo))
您能否提供一个优先级颠倒的示例?
Can you provide an example where the precedence is reversed?
这篇关于为什么 Scala 改变了关系运算符与相等运算符的相对优先级(与 Java 相比)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!