Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you check if a string is not empty or null?

Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string.

Is empty string null in Groovy?

In Groovy, there is a subtle difference between a variable whose value is null and a variable whose value is the empty string. The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.

How do I know if a string is whitespace?

String isBlank() Method This method returns true if the given string is empty or contains only white space code points, otherwise false . It uses Character. isWhitespace(char) method to determine a white space character.


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