Wednesday, October 24, 2007

More Groovy Sugar

Joe Kueser has some excellent posts on Groovy features (What Makes Groovy...So Groovy and More Groovy Goodies) and I would like to attempt to build on them. He has been nice enough to let me borrow The Definitive Guide to Grails, which so far has been an excellent resource for Groovy and Grails (probably one of the best technical books I have read in awhile).

Expando Objects
Joe does a nice job of explaining this handy new class. Here is another example taken from the Grails book by Rocher:

fred = new Expando()

fred.firstName = "Fred"
fred.lastName = "Smith"

fred.age = 40
fred.happyBirthday = {
    fred.age++
}

fred.happyBirthday()
assert fred.age == 41

You can easily play around with this code with groovy's console (/GROOVY_HOME/bin/groovyConsole). As you can see Expando allows you to define an object, its properties, and its methods at run time. Keep in mind that a method is defined by setting a closure to a property that can be later called like a regular method. One immediate use I can see for Expando is in unit tests.

Groovy's == operator
This is very important for existing Java developers. Groovy's == operator is different than Java's in that it does not evaluate object identity, rather it delegates to the object's equals method. To accomplish object comparison, Groovy introduces a new is method: left.is(right).

The Groovy Truth
Term used by Rocher in the Grails book and coined by Dierk Koenig, that explains the Groovy concept of what is true and what is not. Here is an example of what can be passed to if statements in Groovy and will evaluate to false:

  • A null reference
  • An empty or null string
  • The number zero
  • A regex Matcher that doesn't match
This makes those nasty Java if statements much cleaner.

if (str != null && str.length() != 0 )

now becomes

if (str)

More Mt. Dew sugar to come.

2 comments:

Anonymous said...

I didn't know about the == operator, but when you think about it, that's much more intuitive. It does what we all thought == was supposed to do in Java. The .is is quite intuitive too.

Diggin' it!

Jochen "blackdrag" Theodorou said...

you get also "false" for empty lists and maps.