a.ne(null)和a!=Scala中为空?

a.ne(null)和a!=Scala中为空?,scala,null,Scala,Null,我一直在使用 a != null 检查a是否不是空引用。但现在我遇到了另一种方法: a.ne(null) 什么方法更好?它们有什么不同?就像@Jack所说的xnenull等于!(x eq null)。x!=空的和xne空的是=检查值是否相等,ne检查参考值是否相等 例如: scala> case class Foo(x: Int) defined class Foo scala> Foo(2) != Foo(2) res0: Boolean = false scala>

我一直在使用

a != null
检查
a
是否不是空引用。但现在我遇到了另一种方法:

a.ne(null)

什么方法更好?它们有什么不同?

就像@Jack所说的
xnenull
等于
!(x eq null)
x!=空的
xne空的
=检查值是否相等,
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

除了上述@drexin和@Jack之外,
ne
在中定义,并且仅存在于引用类型中

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
scala>“null”.ne(null)
res1:Boolean=true
scala>1.ne(空)
:5:错误:类型不匹配;
找到:Int
必需:?{val ne:?}
请注意,隐式转换不适用,因为它们不明确:
类型为(Int)java.lang.Integer的对象Predef中的两个方法int2Integer
和(Int)scala.runtime.RichInt类型的对象Predef中的方法intWrapper
是从Int到{val ne:?}的可能转换函数
1.ne(空)
scala>1!=无效的
res2:Boolean=true

我不知道scala,但一般来说,如果不知道对象上的方法是否为null,那么调用该方法是不好的。在许多语言中,这会引发“NullPointerException”。@yoshi:这在Scala中不是真的,实际上
null。eq(null)
是完全有效的,返回
true
ne
代表!(这个eq)`)反过来引用您的特定问题:因此,在实践中,与
null
相比,没有区别,对吧?有区别<代码>=可以被覆盖,
ne
不能。另外,
ne
只需检查引用,而
=
可能会检查其他内容。但实际上我仍然不清楚:我应该如何检查字符串参数不为null:with!=或者使用ne?如果您检查
null
,我建议您始终使用
ne
,因为
null
始终是相同的引用,您只想检查它。“并且仅存在于引用类型中”您是指Scala中存在值类型吗?