The Groovy Spaceship Operator Explained

Print Friendly, PDF & Email

Have you ever heard of the spaceship operator? If it is the case, how does it look like? To be honest, I have known it recently when I used this comparison operator to sort an array list of objects. In this post, I will show you what the operator does and how could we apply it into realistic situations.

What is it?

Spaceship operator, originally called three-way comparison and spelt <=>, is used for comparing two objects A and B. This operator returns the values −1, 0, or 1 depending on whether A < B, A = B, or A > B, respectively. There have been a few reasons why it was historically named “spaceship operator” [1]. In my honest opinion, the two symbols < and > look the heads of a spaceship while the symbol = seems to be the body of the spaceship.

PHP 7 introduced the spaceship operator as a new feature [4, 5]. The upcoming C++ spaceship operator has been approved in the proposals for the next C++ standardisation [6, 7].

Spaceship operator In Groovy

Let’s give a piece of code listed below.

def today = new Date()
println today
def yesterday = today - 1
def tomorrow = today + 1
println today <=> today
println today <=> yesterday
println today <=> tomorrow

That piece of code aims to compare Date objects. Obviously, we can evaluate the output of the last three printlnstatement. They produce 0, 1, -1, respectively.

To illustrate what we have done in our work, I will present below how to sort entries of Model of The Month by the publication date. Let’s look at the following lines:

List<ModelOfTheMonthTransportCommand> momEntries = list()
momEntries.sort { m1, m2 -> m2.publicationDate <=> m1.publicationDate }

This results RSS feeds where all entries of Model of The Month were ordered descending by the publication date. See the screenshot below.

In practice, the spaceship operator is often used for sorting objects in arrays or lists. To write this article, I have read the section Spaceship Operator in Groovy’s documentation [2] and a glorious explanation [3].

References

[1] Three-way comparison

[2] Spaceship Operator

[3] The Groovy Spaceship Operator Explained

[4] New features in PHP7

[5] What does this symbol mean in PHP?

[6] Proposals to Fix the Spaceship Operator

[7] Mathematics behind Comparison #1: Equality and Equivalence Relations

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.