Is this a false positive or should I use a better roundabout? (scala identifying Number.NaN)

I’m using sonar-scanner 4.2 to publish report into sonarQube community 8.9.2 with sbt-scoverage 1.6.1 in a scala project

1 reported bug was about rule scala:S1764 Identical expressions should not be used on both sides of a binary operator

The code was something like this : java.text.NumberFormat.getCurrencyInstance(“whatever”).parse(text).filter(num => num == num) which should return a Number

Obviously, the code is quite peculiar, but I didn’t find any other workaround for the spcefic bug we had in production: when the text input has a strange character, the num is a Number.NaN, and I need to filter it out because making operation on this Number will throw an exception. The only solution I found was on Scala Best Practices - Use isNaN when checking for NaN which propose the fast solution of comparing the number to itself since all NaN are different and it will thus return false.
Also, it’s a Number, not a Double, so I can’t use Double.isNan?

Well, it’s either a false positive (abeit in rare case) or there is a better workaround, but I didn’t find any thing elegant. Should I box the value? What should be the most maintenable code for this case?

Thanks for any tips.

1 Like

Hello @antilogos,

Thanks for the report. In your case, it’s indeed a false positive, because this is a valid case for checking if something is NaN or not.

Unfortunately, there is not much we can do to fix it. The current implementation of the scala analyzer relies on the intermediate representation (SLang) and it doesn’t use semantics. So we can’t track types. So in your case, this would make the detection of such corner cases extremely hard And might not be worth it.

I suggest you just mark it as a false positive.