My method is as follows
def myMethod(myDouble: Double): Double = myDouble match { case Double.NaN => ... case _ => ... }
The IntelliJ debugger is showing NaN but this is not being picked up in my pattern matching. Are there possible cases I am omitting
Scala Float isNaN() method with exampleThe isNaN() method is utilized to return true if this Float value or the specified float value is Not-a-Number (NaN), or false otherwise. Return Type: It returns true if this Float value or the specified float value is Not-a-Number (NaN), or false otherwise.
Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.
Notes. Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With