为什么在 case 类的 `unapply` 方法的实现中有一个 `null` 检查? [英] Why is there a `null` check in the implementation of the `unapply` method for case classes?
问题描述
我正在努力用我自己的实现替换案例类的伴随对象上的 unapply
方法.在调查了与实现 unapply
相关的许多不同切线之后,似乎在大多数情况下都有一个 null
保护,无论是在编译器生成的代码中还是在它的实现中明确地被重新定义.编译器为 unapply
生成的代码看起来与此类似(其中一些使用 eq
而不是 ne
):
I'm working to replace the unapply
method on a case class's companion object with my own implementation. And after investigating lots of different tangents related to implementing unapply
, it appears there is a null
guard in most of them, both in the compiler generated code and in the implementations where it is explicitly being redefined. The code from the compiler generated code for unapply
looks similar to this (some of them use eq
instead of ne
):
def unapply(location: Location): Option[(Double, Double)] =
if (location ne null)
Some((location.longitude, location.latitude))
else
None
鉴于在纯(即惯用的)Scala 代码中绝对不应该使用 null
,为什么要执行此 null
检查?是否与 Java 互操作(因为 Java 仍然沉迷于利用 null
)泄漏到 unapply
方法有关?如果因为我已经消除了传递 unapply
方法的 case 类实例可以为 null 或无效的可能性而删除检查,我会遭受什么(如果有的话)不良后果?IOW,用这个替换上面的实现有什么害处?
Given there should be absolutely no use of null
in pure (i.e. idiomatic) Scala code, why is this null
check being performed? Does it have something to do with Java interop (because Java is still addicted to exploiting null
) leaking into the unapply
method? What, if any, undesirable consequences will I suffer if I remove the check because I have eliminated the possibility of the case class instance to which the unapply
method is being passed can be null nor invalid? IOW, what's the harm of replacing the above implementation with this one?
def unapply(location: Location): Option[(Double, Double)] =
Some((location.longitude, location.latitude))
推荐答案
否则,这将产生非常令人惊讶的行为:
Otherwise, this would give very surprising behavior:
nullableJavaMethod() match {
case Location(lat, long) => "Handle location here!"
case null => "Handle null here!"
}
您可能更喜欢另一种处理 null 的方法,但这并不意味着如果有人更喜欢这种方法,您应该使用 NPE 进行上述崩溃.请注意,这是特定于 unapply
的,因为其他方法不会遇到上述问题.
You might prefer another approach to handling null, but that doesn't mean you should make cases like the above crash with NPE if someone prefers that approach. Note that this is specific to unapply
, as other methods will not suffer from the problem above.
这篇关于为什么在 case 类的 `unapply` 方法的实现中有一个 `null` 检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!