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
Interpreting Spatial Data in the Age of COVID-19
As 2020 has come to an end, many are eager to leave the mess of COVID-19 behind with the new year and gain a fresh start. Unfortunately, new cases are still soaring across the United […]
Building a Better Mousetrap
Recently, my daughter (age 6) was into building “mousetraps” out of shoe boxes. These were more or less comfortable cardboard mouse houses complete with beds, rooms, everything a mouse could want or need and not […]
ARM Wrestling Its Way Into Mainstream Software Development
Nearly all smart phones have been running ARM-based processors for years. They provide superior power for the amount of power consumed, and thus extend battery life. With Apple’s recent release of the Apple Silicon M1 […]
Video capture using WebRTC
Capturing the feed of a users camera can be a daunting undertaking involving one or multiple third party packages. Often we opt for prompting the user to upload the video or image we need, causing […]