为什么 !== 在 Scala 中的优先级低于 === ?
Why has !== lower precedence than === in Scala?
以下代码无法编译:
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),因此 !==
的优先级应该与 ===
、[=14= 的相同] 或 ==
.
为什么上面的代码需要括号?
答案在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 (<=), (>=), (!=).
根据这些规则,!==
被认为是赋值运算符,而 ===
不是。
以下代码无法编译:
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),因此 !==
的优先级应该与 ===
、[=14= 的相同] 或 ==
.
为什么上面的代码需要括号?
答案在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 (<=), (>=), (!=).
根据这些规则,!==
被认为是赋值运算符,而 ===
不是。