以下代码无法编译:
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/