Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare for null in groovy correctly?

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.

like image 230
bish Avatar asked Dec 19 '14 09:12

bish


People also ask

How do I check for null objects in Groovy?

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.

How do you compare null?

We can simply compare the string with Null using == relational operator. Print true if the above condition is true. Else print false.

Is null true in groovy?

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.

How do I compare two values in groovy?

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.


1 Answers

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?

like image 161
Opal Avatar answered Oct 11 '22 19:10

Opal