scala && 和 || 在斯卡拉

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3916207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:30:00  来源:igfitidea点击:

&& and || in Scala

scalaif-statement

提问by mice

since normal operators like +, ::, -> and so on are all methods which can be overloaded and stuff I was wondering if || and && are methods as well. This could theoretically work if this were methods in of the boolean object. But if they are, why is something like

因为像 +、::、-> 等普通运算符都是可以重载的方法,我想知道是否 || 和 && 也是方法。如果这是布尔对象的方法,这理论上可以工作。但如果他们是,为什么是这样的

if (foo == bar && buz == fol)

possible? If the compiler reads from right to left this would invoke && on bar instead of (foo == bar)

可能的?如果编译器从右到左读取,这将在 bar 上调用 && 而不是 (foo == bar)

回答by Daniel C. Sobral

6.12.3 Infix Operations An infix operator can be an arbitrary identifier. Infix operators have precedence and associativity defined as follows:

The precedence of an infix operator is determined by the operator's first character. Characters are listed below in increasing order of precedence, with characters on the same line having the same precedence.

6.12.3 中缀操作中缀操作符可以是任意标识符。中缀运算符的优先级和结合性定义如下:

中缀运算符的优先级由运算符的第一个字符决定。下面按优先级递增的顺序列出字符,同一行中的字符具有相同的优先级。

  • (all letters)
  • |
  • ^
  • &
  • < >
  • = !
  • :
  • + -
  • * / %
  • (all other special characters)
  • (所有字母)
  • |
  • ^
  • &
  • < >
  • =!
  • + -
  • * / %
  • (所有其他特殊字符)

That is, operators starting with a letter have lowest precedence, followed by operators starting with ‘|', etc.

There's one exception to this rule, which concerns assignment operators(§6.12.4). The precedence of an assigment operator is the same as the one of simple assignment (=). That is, it is lower than the precedence of any other operator.

也就是说,以字母开头的运算符的优先级最低,其后是以“|”开头的运算符,以此类推。

此规则有一个例外,它涉及赋值运算符(第 6.12.4 节)。赋值运算符的优先级与简单赋值(=)相同。也就是说,它低于任何其他运算符的优先级。

It follows with an explanation of associativity, and how it all combines in a expression with multiple operators. The Scala Referencemakes good reading.

接下来是对结合性的解释,以及它如何在具有多个运算符的表达式中组合。在斯卡拉参考,使良好的阅读。

回答by Brian Hsu

Because method starts with = has a higher precedence than method starts with &.

因为以 = 开头的方法比以 & 开头的方法具有更高的优先级

So (foo == bar && buz == fol) will become something like the following:

所以 (foo == bar && buz == fol) 将变成如下所示:

val tmp1: Boolean = (foo == bar)
val tmp2: Boolean = (buz  == fol)

tmp1 && tmp2

回答by lasantha

Those two are definitely methods in scala.

这两个绝对是scala中的方法。