Saturday, March 4, 2017
More Groovy Sugar
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 groovys 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.
Groovys == operator
This is very important for existing Java developers. Groovys == operator is different than Javas in that it does not evaluate object identity, rather it delegates to the objects 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 doesnt match
if (str != null && str.length() != 0 )
now becomes
if (str)
More Mt. Dew sugar to come.
Available link for download