gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:44:36 25 4
gpt4 key购买 nike

以下代码无法编译:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com