scala - 为什么 !== 在 Scala 中的优先级低于 ===?

标签 scala operator-overloading operator-precedence

以下代码无法编译:

implicit class TripleEq(val x: Int) {
  def === (y: Int) = x == y
  def !== (y: Int) = x != y
}

val a = 0
val b = 1

if (a == a && b === b) {
  println("Equal")
}

if (a != b && a !== b) {
  println("Not equal")
}

错误是:

type mismatch; found : Int required: Boolean



当我附上 a !== b 时,错误消失了在括号内。

我认为运算符优先级由它的第一个字母定义(见 Tour of Scala ),因此 !== 的优先级应与 === 相同, !=== .

为什么上面的代码需要括号?

最佳答案

答案在 Assignment Operators 的语言规范中:

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

6.12.14 Assignment Operators

An assignment operator is an operator symbol (syntax category op in Identifiers) that ends in an equals character “=”, with the exception of operators for which one of the following conditions holds:

  • the operator also starts with an equals character, or
  • the operator is one of (<=), (>=), (!=).

基于这些规则!==被认为是赋值运算符,而 ===不是。

关于scala - 为什么 !== 在 Scala 中的优先级低于 ===?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60015893/

相关文章:

c++ - 为什么 "- --"和 "+++"和 操作不同?

scala - 如何展平析取类型

c++ - 重载方括号运算符以接受值

c++ - 在什么情况下会调用类型自身的转换运算符?

c# - 使用数组索引时的操作顺序

javascript - Math.floor(Math.random() * 5 + 1) 的操作顺序?

scala - 在 Scala 中拦截套接字关闭上的 Akka HTTP WebSocket 事件

scala - 如何更改功能测试的 Guice 绑定(bind)?

scala - 如何在游戏 2.3.0 中使用 securesocial

operator-overloading - 不能为我的类(class)重载逻辑运算符(或、和)