How to compare for null in groovy correctly?
Asked Answered
F

2

11

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.

Forficate answered 19/12, 2014 at 9:37 Comment(0)
B
13

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?

Beaut answered 19/12, 2014 at 9:41 Comment(2)
yes. see the debug line println "row6: " + row[6] which results in row6: null. Also in my script when the script enters the else-part it crashs cause of Null Pointer Exception when trying to convert the null to int: Data conversion error converting "'null' (yyy: xxx INT)"Forficate
Provide the full example.Beaut
A
0

This code prints the output from the question:

def row = []
row[6] = "null"
println "row6: " + row[6]

if(row[6] == null) {
  println "if"
} else {
  println "else"
}

So it should be evident that row[6] is not null but a string containing "null".

Antimonic answered 27/4, 2023 at 16:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.