a.ne之间的区别是什么(空)和!=在斯卡拉空?(What is the difference be

2019-06-23 11:12发布

我一直一直使用

a != null

检查a是不是空引用。 但现在我已经见过用另一种方式:

a.ne(null)

什么样的方式更好,他们如何不同?

Answer 1:

就像@Jack说x ne null等于!(x eq null) 。 之间的差x != nullx ne null在于!=对值相等,并检查ne参考相等检查。

例:

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


Answer 2:

除此之外说@drexin和@Jack, ne定义AnyRef和只存在引用类型。

scala> "null".ne(null)
res1: Boolean = true

scala> 1.ne(null)
<console>:5: error: type mismatch;
 found   : Int
 required: ?{val ne: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method int2Integer in object Predef of type (Int)java.lang.Integer
 and method intWrapper in object Predef of type (Int)scala.runtime.RichInt
 are possible conversion functions from Int to ?{val ne: ?}
       1.ne(null)

scala> 1 != null
res2: Boolean = true


文章来源: What is the difference between a.ne(null) and a != null in Scala?
标签: scala null