Scala 中的 a.ne(null) 和 != null 有什么区别?
问题描述:
我一直在用
a != null
检查 a
不是空引用.但现在我遇到了另一种使用方式:
to check that a
is not a null reference. But now I've met another way used:
a.ne(null)
哪种方式更好,它们有何不同?
what way is better and how are they different?
答
就像@Jack 所说的 x ne null
等于 !(x eq null)
.x != null
和 x ne null
的区别在于 !=
检查值是否相等和 ne
检查供参考相等.
Like @Jack said x ne null
is equal to !(x eq null)
. The difference between x != null
and x ne null
is that !=
checks for value equality and ne
checks for reference equality.
示例:
scala> case class Foo(x: Int)
defined class Foo
scala> Foo(2) != Foo(2)
res0: Boolean = false
scala> Foo(2) ne Foo(2)
res1: Boolean = true