How can I determine if a String is non-null and not only whitespace in Groovy?

I find this method to be quick and versatile:

static boolean isNullOrEmpty(String str) { return (str == null || str.allWhitespace) } 

// Then I often use it in this manner
DEF_LOG_PATH = '/my/default/path'
logPath = isNullOrEmpty(log_path) ? DEF_LOG_PATH : log_path

I am quite new to using groovy, though, so I am not sure if there exists a way to make it an actual extension method of the String type and this works well enough that I have not bothered to look.

Thanks, -MH


It's works in my project with grails2.1:

String str = someObj.getSomeStr()?.trim() ?: "Default value"

If someObj.getSomeStr() is null or empty "" -> str = "Default value"
If someObj.getSomeStr() = "someValue" -> str = "someValue"


Another option is

if (myString?.trim()) {
  ...
}

(using Groovy Truth for Strings)


You could add a method to String to make it more semantic:

String.metaClass.getNotBlank = { !delegate.allWhitespace }

which let's you do:

groovy:000> foo = ''
===> 
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true