Using spaceship operator

One of the coolest things in groovy – is a spaceship operator.
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.While the spaceship could be used wherever you would use compareTo(), it seems most references to it are found in sorting.

Nice and easy to understand article about it can be found hereReally the greatest advantage of using the Groovy comparison operators is the graceful handling of nulls such that

x <=> y
will never throw a NullPointerException:


// This does not work
[14, null, 7, 'c'].sort{a,b-> a > b}

// This sorts fine
[14, null, 7, 'c'].sort{a,b-> a <=> b}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s