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

cdeszaq picture cdeszaq · Feb 6, 2012 · Viewed 169.5k times · Source

Groovy adds the isAllWhitespace() method to Strings, which is great, but there doesn't seem to be a good way of determining if a String has something other than just white space in it.

The best I've been able to come up with is:

myString && !myString.allWhitespace

But that seems too verbose. This seems like such a common thing for validation that there must be a simpler way to determine this.

Answer

tim_yates picture tim_yates · Feb 7, 2012

Another option is

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