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

Solution 1:

Another option is

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

(using Groovy Truth for Strings)

Solution 2:

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