Shabar
Shabar

Reputation: 2821

Null and empty check in one go in groovy

Can someone please clarify below issue.

Below validation throw NULL pointer error when pass null in myVar. It is because of !myVar.isEmpty()

if (myVar!= null || !myVar.isEmpty() ) {
             
             some code///
                }

Below works though as expected,

if (myVar!= null) {
        if (!myVar.isEmpty()) {
             some code///

                }

Any other way of having both steps together.

Upvotes: 5

Views: 44884

Answers (3)

Campfire
Campfire

Reputation: 894

Besides the groovy-specific answers that show better ways to check the content of a variable, the boolean operator you use is incorrect. There has to be a logical AND between the two terms:

myVar != null && !myVar.isEmpty()

In this case, if myVar actually is null (=false), the second part of the expression is no longer evaluated because the complete expression cannot turn true anymore. The logical OR on the other hand forces the evaluation of the second part of term and fails when myVar is null.

There's a difference between the language-based "I don't want to do this if this or that is true" and the logical OR.

Upvotes: 0

daggett
daggett

Reputation: 28564

if ( myVar!= null && !myVar.isEmpty() ) {
    //some code
}

the same as

if ( !( myVar== null || myVar.isEmpty() ) ) {
    //some code
}

and to make it shorter - it's better to add method like hasValues

then check could be like this:

if( myVar?.hasValues() ){
    //code
}

and finally to make it groovier - create a method boolean asBoolean()

class MyClass{
    String s=""
    boolean isEmpty(){
        return s==null || s.length()==0
    }
    boolean asBoolean(){
        return !isEmpty()
    }
}

def myVar = new MyClass(s:"abc")

//in this case your check could be veeery short
//the following means myVar!=null && myVar.asBoolean()==true
if(myVar) {
    //code
}

Upvotes: 5

cfrick
cfrick

Reputation: 37008

If .isEmpty() is used on a string, then you can also just use Groovy "truth" directly, as null and also empty strings are "false".

[null, "", "ok"].each{
    if (it) {
        println it
    }
}
// -> ok

Upvotes: 13

Related Questions