In Scala, why is NaN not being picked up by pattern matching?

It is a general rule how 64-bit floating point numbers are compared according to IEEE 754 (not Scala or even Java related, see NaN):

double n1 = Double.NaN;
double n2 = Double.NaN;
System.out.println(n1 == n2);     //false

The idea is that NaN is a marker value for unknown or indeterminate. Comparing two unknown values should always yields false as they are well… unknown.


If you want to use pattern matching with NaN, try this:

myDouble match {
    case x if x.isNaN => ...
    case _ => ...
}

But I think pattern matching will use strict double comparison so be careful with this construct.

Leave a Comment

tech