I’ve been digging into Groovy in Action lately. I read the .75 review copy, which was extremely cool. The final release of the book included a ton of even cooler stuff!

One thing that did appear in the final version was a ton of interesting reference information, including very comprehensive tables in the body of the text. One of the operators I hadn’t seen before was the “spaceship operator” <=>. Now I remember this bad boy from my Perl days, but I didn’t know Groovy had an equivalent.

So when might you use this guy? Whenever you need to implementing sorting in a hurry, like implementing a compareTo(). The spaceship will return -1 if the left side is smaller, 1 if the left side is greater, and 0 if both sides are equal. Perfect for sorting, no? Seeing it in action makes it clearer…

println 3 <=> 4
println "glen" <=> "dierk"
def d = new Date()
println d <=> d
println d <=> new Date()

Which gives you....

-1
1
0
-1

Turns out that I have an immediate use for it. I’m working on fixing some nasty bugs in my dodgy chart generation code for groovyblogs. The good old spaceship is going to make some of my sorts one-liners.

How groovy is that? Beam me up!