cdeszaq
cdeszaq

Reputation: 31280

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

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.

Upvotes: 179

Views: 310325

Answers (4)

MostHated
MostHated

Reputation: 150

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.

Upvotes: 2

in_trance
in_trance

Reputation: 51

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"

Upvotes: 5

tim_yates
tim_yates

Reputation: 171084

Another option is

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

(using Groovy Truth for Strings)

Upvotes: 341

doelleri
doelleri

Reputation: 19682

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

Upvotes: 11

Related Questions