What is the difference between a.ne(null) and a != null in Scala?

感情迁移 提交于 2019-12-18 18:55:58

问题


I have been always using

a != null

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?


回答1:


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.

Example:

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



回答2:


Besides that said @drexin and @Jack, ne defined in AnyRef and exists only for referential types.

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


来源:https://stackoverflow.com/questions/10066927/what-is-the-difference-between-a-nenull-and-a-null-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!