Groovy is whack UNLESS it’s more like Ruby

Here’s a little script I whipped up this morning in literally one minute after reading a thread on the Groovy mailing list. The thread author wanted an unless keyword added to Groovy because, well most likely because some other language he was used to supported it. The thing with Groovy is you can do anything you want with the language even turn it into a completely different language on the fly with very little programming effort. So in order to fulfill the request I set out to add the unless keyword to the Groovy arsenal. Bear in mind that I spent only one minute on the code, it is not powering any mission critical apps, I have not studied the logic or run it through a battery of tests. Let’s just call it a hack that works unless something is broken.

class Conditions {
   public static void unless(Object obj, boolean cond, Closure work) {
      if(! cond) work()

use(Conditions) {
   unless( 1+1 > 2 ) { println 'Math is working' }
   unless( 5 > 1 ) { println 'Conditions do not work.' }

When I run that snippet I get: ‘Math is working’ printed to the console. So yes, a native unless keyword is not included with Groovy (neither are batteries! For some odd reason many manufacturers seem to enjoy the thought of a kid whimpering over a functionally dead toy on Christmas morning … sorry I’m off topic again…) but through a one minute hack you can add unless and many other missing keywords to your arsenal.

One thought on “Groovy is whack UNLESS it’s more like Ruby

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s