I'm curious what cool uses people have found for Groovy. (beyond a Grails app)
MIne is being able to write Hudson/Jenkins scripts to run in the Groovy console. It's awesome being able to fix the parent jobs of hundreds of projects in just a few lines of code. Or write queries/reporting in just a few lines of code.
Bear Bibeault wrote:Don't know how cool it is, but the Play! framework (version 1) templates use Groovy rather than JSP. (Version 2 uses Scala templates.)
So people can put too much Groovy code in the template instead of too much Java code?
LOL! Yeah, those without discipline can create really poor templates. But in a lot of ways it's very very cool.
Two things I really like:
The "Elvis" operator: ?: (great for supplying defaults on false/null).
"Safe nav" operator: short-circuits null references. The expression user?.company?.address?.city produces null, rather than an NPE, if any reference is null.
Kenneth A. Kousen
gunslinger & author
Joined: Sep 18, 2002
Speaking of the Elvis operator, try this one:
That's a sort by length, and if the lengths are equal (i.e., the sizes are the same so <=> returns 0), it sorts lexicographically (which is alphabetically with capital letters ahead of lowercase letters). More importantly, it shows Elvis being carried back to his home planet by two tandem spaceships, so it's the fat Elvis from the 70s rather than the thin Elvis from the 50s.
Yeah, that's a long way to go for such a silly gag, but I still find it amusing. More generally, if you wanted to sort strings by length in Java, you'd write:
The Groovy JDK adds a sort method to collections, so you don't need the Collections class at all. The sort method also takes a one- or two-argument closure. If you use the two-arg closure, you supply a typical comparator, as in:
If you use the one-arg closure, then just return something that can be used for the sort (typically an integer), so the whole length sort reduces to:
and you're done. Hard to be much simpler than that.
author & internet detective