Null and empty check in one go in groovy
Asked Answered
S

3

5

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.

Sinking answered 11/2, 2021 at 0:21 Comment(0)
E
13

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
Evannia answered 11/2, 2021 at 7:30 Comment(0)
G
5
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
}
Gunman answered 11/2, 2021 at 1:25 Comment(3)
In the above case when pass myVar as NULL it go inside the code. Because second check !myVar.isEmpty() gives this Cannot invoke method isEmpty() on null objectSinking
@SMPH Not in any sane programming language, because if is short-circuitingEvannia
@SMPH, i've updated an answer. and for your comment: i'm using && to join expressions a!=null && !a.isEmpty(). in case when a=null the first part returns false and it's not necessary to execute the second part because false && any returns false. so groovy (and all other languages) are not executing the second part after && if first one returns falseGunman
R
0

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.

Ridinger answered 23/9 at 9:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.