Between null and positive infinity

Posted by Marcin on Friday, August 19, 2016

Problem

I happen to create a construction like this:

if(object?.value > 0) {
    println "do something"
} else {
    println "do nothing"
}

Are you sure what will be printed when object is null? I must say I wasn’t.

We got used to negate null in groovy like this:

assert !null == true   

but what about using null with relation operator?

Comparing null

Let us review below code:

assert null < 0

assert null < Integer.MIN_VALUE
assert null < Double.NEGATIVE_INFINITY

assert null < Integer.MAX_VALUE
assert null < Double.POSITIVE_INFINITY

In each of these cases, the assertion passes without errors. This behavior might seem counterintuitive at first glance.

Turns out

When comparing null with a positive number, null is treated as the lowest possible value, akin to negative infinity. Therefore, null is considered less than any positive number, regardless of its magnitude.

So lets remember.. null is the lower then anything :)

Watch out doing comparisons like the one on top, as you might get unexpected results.


comments powered by Disqus