How to compare for null in groovy correctly? - groovy

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.

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?

Related

variables in groovy how to set a condition by variable type

I'm a total newbie and I'm looking for some advice.
how to make a condition in Groovy so that if the variable is a string, then one action is performed, and if the sheet is another
and just as it is necessary to do, if the variable is equal to zero, then nothing is transmitted
//aditionalArgs= "test1 = add1 , tets2= add2 "
aditionalArgs = ["test1=arg1", "test2=arg2"]
println(aditionalArgs.class)
def args = ""
if ((aditionalArgs != "class java.lang.String" ) || (aditionalArgs > 0)){
def list = aditionalArgs.replace("--build-arg", "").split(',')
list.each { val->
args += " --build-arg $val"
}
println(args.replace("",""))
}
if (aditionalArgs == "ArrayList" ){
def list = aditionalArgs("--build-arg", "").split('[' , ']')
list.each { val->
args += " --build-arg $val"
}
println(args.replace("",""))
}
else(aditionalArgs.length() > 0){
println "empty aditionalArgs"
}```
if (aditionalArgs instanceof String && aditionalArgs.length() > 0) {
...
} else if (aditionalArgs instanceof List && aditionalArgs.size() > 0) {
...
} else {
println "unsupported arg type '${aditionalArgs?.getClass()}' or value '${aditionalArgs}'"
}
Your code suggests that you rather want to use a switch op:
switch( aditionalArgs ){
case String:
// do stuff with String
break
case List:
// do stuff with (Array)List
break
case Number:
// do something with Number
break
default:
throw new Exception( 'I have no idea' )
}
More on the statement is in the docs

Scanner() not working with if - else statement

My intention is to let the user decide which method to use by cheking its input.
I have the following code:
try {
String test = scan.next();
if(test == "y") {
//do stuff
}
else if (test == "n") {
//do stuff
}
} catch (Exception e) {
System.out.println("false");
}
I tried to analyze with the debugger. It is not jumping in the if-statement.
can you help me out here?
You need to use equals to compare strings
if(test == "y")
becomes
if (test.equals("y"))
Same for "n" obviously.
== test for reference equality, but you're looking for value equality, that's why you should use equals, and not ==.

How to handle if no rows returned in Groovy

I have the following piece of code:
sql.eachRow(query){
def i=1
println("$i --> $it.columnName")
i++
}
If query returns some records(rows), there is no problem.
But if query is returning 0 records then how should I handle it. I want to show a user-friendly message, such as ZERO RECORDS FOUND.
def i=0
sql.eachRow(query) {
i++
println(i+" --> "+ it.columnName)
}
if (i == 0) {
println "ZERO RECORDS FOUND"
}
def rows = sql.rows(query)
if (rows.empty) {
// logic for handling no rows
} else if (rows.any { it.name == 'something' }) {
// logic for handling isExists == true
} else {
// logic for handling isExists == false
}
I'm not sure what's your specific case is, but it may be a case that checking name == 'something' condition can be done straight away at SQL level with WHERE name = 'something'. Then you could get rid off one of logical blocks in if statement.

Test only if variable is not null in if statement

I have the following method where I want to test the event.status property only if status has been passed in:
def findEvent(String desc, String status = null, Collection events) {
return events.find {
it.description == desc && \\If status is not null: it.status == status
}
throw new Exception("Review Event Record Not Found: ${desc}")
}
I thought it could be done like this, but it doesn't seem to work:
def findEvent(String desc, String status = null, Collection events) {
return events.find {
it.description == desc && (status != null ?: {it.status == status})
}
throw new Exception("Review Event Record Not Found: ${desc}")
}
Is there any way this could be done? Or do I have to go back to something like this:
if (status != null) {
return events.find {
it.description == desc && it.status == status
}
} else if (status == null) {
return events.find {
it.description == desc
}
}
Is there some kind of best practice?
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

using ExpandoMetaclass in groovy print result and null value also

the sample progame when i try to run using the expandometaclass technique it give me two output one the desired result second one "null" as output, from where null is picked up ?
class testA {
static def X(def var) {
Y(var)
}
static def Y(def var) {
println var
}
}
testA.metaClass.static.newMethod = {z_var -> X(z_var) }
println testA.newMethod("anish")
output:
anish
**null**
why this progranme also print null as output
The null is the return value from newMethod. In case you don't want this to be printed remove the println from your line
println testA.newMethod("anish")

Resources