chaotic3quilibrium
chaotic3quilibrium

Reputation: 5924

Why is there a `null` check in the implementation of the `unapply` method for case classes?

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

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))

Upvotes: 2

Views: 146

Answers (1)

Brian McCutchon
Brian McCutchon

Reputation: 8594

Otherwise, this would give very surprising behavior:

nullableJavaMethod() match {
  case Location(lat, long) => "Handle location here!"
  case null => "Handle null here!"
}

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.

Upvotes: 1

Related Questions