groovy

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.


Solution

  • 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