gpt4 book ai didi

scala - scala 中 null 的相等性,odersky 书的解释似乎与 scala 代码不同?

转载 作者:行者123 更新时间:2023-12-01 08:27:44 25 4
gpt4 key购买 nike

在 Odersky 的书“Programming in Scala”第二版第 89 页第 5.7 节中,“==”运算符解释为:

"As you see, == has been carefully crafted so that you get just the equality comparison you want in most cases. This is accomplished with a very simple rule: first check the left side for null, and if it is not null, call the equals method...Since there is an automatic null check, you do not have to do the check yourself (7)"

然后是音符“7”:

"The automatic check does not look at the right-hand side, but any reasonable equals method should return false if its argument is null."

如果 null 检查不查看 RHS,我希望 null==anything 总是评估为 false...但我试过了,null==null 评估为 true。

本书基于scala 2.8。语言是否在某个时候发生了变化,或者我只是误解了解释?

在我使用的 drools 引擎中,== 被解释为如果 LHS 为空且 RHS 不为空,则 RHS 中的 equals 方法将传递给 LHS。尽管最合理的 equals 方法应该在 null 时返回 false,但我喜欢 drools 引擎处理这个问题的方式。在 SQL 中,我习惯于 null != null。

最佳答案

在我看来,引用的文字只说明了如果 LHS 不是 null 会发生什么,所以那部分没有矛盾。当 LHS 为 null 时发生的情况的描述可能在您没有引用的文本的某些部分中,或者它完全丢失了。

注释(7) 说明,如果LHS 不是null,则不会对RHS 执行任何检查,RHS 只是传递给equals。因此,当比较诸如 someExpression == null 之类的内容时,Scala 首先检查 someExpression 是否不为 null,然后调用 someExpression.equals(null)

我会说 Scala 的 term1 == term2 被转换成 Java 的

(term1 != null) ? term1.equals(term2) : (term2 == null)

(请注意,这是一个 Java 代码片段,所以上一行中的 == 表示 Java 的引用相等性。)

关于scala - scala 中 null 的相等性,odersky 书的解释似乎与 scala 代码不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12638925/

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