Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mathifonseca/2feaa410d3154e86a2ec to your computer and use it in GitHub Desktop.
Save mathifonseca/2feaa410d3154e86a2ec to your computer and use it in GitHub Desktop.
GRAILS - Custom Groovy Truth

I know it's a dangerous thing, it can generate confusion and unwanted magical happenings, but...

The Groovy Truth is what makes collections evaluate as false when they are null or empty, or Numbers evaluate as false when its value is null or zero and true otherwise.

As with many other operators and defult Groovy methods, you can add this magic to an object of your own. Just by overriding its asBoolean method.

For example, here is my Order class.

class Order {
	boolean active
	List items
}

Imagine that anywhere I work with an object of this class, I need to know if it is active and it has items. This would look like this:

if (order.active == true && order.items.size() > 0) {
	//do sth with the order
}

Yes, I know I can make it shorter by using the default Groovy truth for that boolean field and the collection of items. That will make the condition look like this:

if (order.active && order.items) {
	//do sth with the order
}

But the real magic happens when I add this method to the Order class:

boolean asBoolean() {
	return active && items
}

From now on, the whole object will evaluate to true if its active property is true and its items property is not null and not empty. Although this can lead to some confusions, this is usually what I want to ask to determine if I can work with that order instance or not.

So this is how that if would look like now:

if (order) {
	//do sth with the order
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment