edit: Stupid. The problem was that I got a string with value 'null'
How to compare for null in groovy correctly?
I've got the following script
println "row6: " + row[6]
if(row[6] == null) {
println "if"
}
else {
println "else"
}
When I run it with a row where the specified field is null this is the output:
row6: null
else
The Groovy Docs say a == null
will work, while a.is(null)
will not.
So how do I compare for null in groovy the right way?
P.S. I saw The SO-Thread: comparing-null-and-number-in-groovy. It says that null is handled as a number, but this would still mean a ==
comparision should work when the value is null.
In Groovy we can do this shorthand by using the null safe operator (?.). If the variable before the question mark is null it will not proceed and actually returns null for you.
We can simply compare the string with Null using == relational operator. Print true if the above condition is true. Else print false.
A null object always coerces to false. Type conversion method for null. The method "is" is used to test for equal references. iterator() method to be able to iterate on null.
Groovy - compareTo() The compareTo method is to use compare one number against another. This is useful if you want to compare the value of numbers.
This code prints if:
def row = []
row[6] = null
println "row6: " + row[6]
if(row[6] == null) {
println "if"
} else {
println "else"
}
Are you sure that row[6]
is null?
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