Feb 8, 2010

The Groovy Spaceship Operator Explained

While extending an existing Grails application bits of research around sorting lists using Groovy ensued. My first stop was Groovy In Action wherein the operator <=> was shown in a closure used for sorting, but with no explanation. Under Operators in the index, it became known that <=> is “The Spaceship Operator” – no doubt due to its similarity in look to a flying saucer. Sadly the referenced section of text also offered little in explaining what this bugger did exactly.

The spaceship operator has it’s roots in Perl and has found it’s way in to languages like Groovy and Ruby. The spaceship is a relational operator that performs like Java’s compareTo() comparing two objects and returning -1, 0, or +1 depending on the value of the left argument as compared to the right. If the left argument is greater than the right, the operator returns 1. If the left argument is less than the right, the operator returns −1. If the arguments are equal, 0 is returned. When using Groovy/Grails, if the arguments are not of comparable types, a ClassCastException is thrown.

While the spaceship could be used wherever you would use compareTo(), it seems most references to it are found in sorting. For example the following two lines would have identical results:

things.sort{ Thing a, Thing b -> b.beginDate <=> a.beginDate }

things.sort{ Thing a, Thing b -> b.beginDate.compareTo( a.beginDate ) }

Other examples of its behaviour from the Groovy Console:

groovy> def d = new Date()
groovy> println d <=> d
groovy> println 3 <=> 4
groovy> println “doberman” <=> “dachshund”
groovy> println d <=> new Date()

0
-1
1
-1

Perhaps the greatest advantage of using the Groovy comparison operators is the graceful handling of nulls such that x <=> y will never throw a NullPointerException:

groovy> println “dachshund” <=> null
groovy> println null <=> “dachshund”
groovy> println null <=> null

1
-1
0

In addition when comparing numbers of different types the type coercion rules apply to convert numbers to the largest numeric type before the comparison. So the following is valid in Groovy1:

groovy> Byte a = 27
groovy> Double b = 9
groovy> println a instanceof Byte
groovy> println b instanceof Double
groovy> println a > b

true
true
true

We come in peace – happy comparisons! For more on Groovy operator overloading look here.

1 “Groovy – Operator Overloading” Available at: http://groovy.codehaus.org/Operator+Overloading 26 January 2010

About the Author

Object Partners profile.

One thought on “The Groovy Spaceship Operator Explained

  1. Paras Jain says:

    Thanks. I was not even aware that we have such operator in Groovy. Will try in some places where we have sorting operations.

  2. F.Baube says:

    What’s old is new again. In FORTRAN this was called an “arithmetic IF”, look it up 🙂

  3. cease says:

    what resources do you use for groovy, like did you find this in a book anywhere ?

  4. Brad Karels says:

    I am fortunate that here at Object Partners Inc. we have very solid, core group of developers with a lot of depth in both Groovy and Grails – the whole ‘shoulders of giants’ thing. Beyond that, Groovy In Action, of course is one of my staple resources as well as the information available at http://groovy.codehaus.org/. Also, while Grails centric, http://www.grails.org/doc/latest/ has allowed me to piece together bits of functionality to create my desired outcome.

    Despite the wonderful nature of Groovy and Grails, one of the great frustrations is the holes in the books and online resources, a lot of which is just dead wrong. I find the best course is to ask a lot of questions when you have an expert available, ask thorough and well formed questions with source code in the forums, and find some good bloggers to follow. Some other resources that have helped me along the path are:

    * Follow @groovytweets on twitter
    * The Definitive Guide to Grails, Second Edition
    * Groovy in Action
    * http://groovy.codehaus.org
    * http://www.objectpartners.com/weblog/
    * http://www.grails.org/
    * …and countless hours on ‘the google’, transient blogs, and user groups.

  5. Axel Brinkop says:

    I just was stumpling across the following difference:
    assert ‘aaa’.compareTo(‘aaz’) == -25;
    assert (‘aaa’ ‘aaz’) == -1;

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Blog Posts
Google Professional Machine Learning Engineer Exam 2021
Exam Description A Professional Machine Learning Engineer designs, builds, and productionizes ML models to solve business challenges using Google Cloud technologies and knowledge of proven ML models and techniques. The ML Engineer is proficient in all aspects […]
Designing Kubernetes Controllers
There has been some excellent online discussion lately around Kubernetes controllers, highlighted by an excellent Speakerdeck presentation assembled by Tim Hockin. What I’d like to do in this post is explore some of the implications […]
React Server Components
The React Team recently announced new work they are doing on React Server Components, a new way of rendering React components. The goal is to create smaller bundle sizes, speed up render time, and prevent […]
Jolt custom java transform
Jolt is a JSON to JSON transformation library where the transform is defined in JSON. It’s really good at reorganizing the json data and massaging it into the output JSON you need. Sometimes, you just […]