Dark theme | Light theme

August 26, 2009

Groovy Goodness: the Spaceship Operator

Groovy adds some nice operators to the language. One of them is the spaceship operator. It's called the spaceship operator, because we use the following syntax <=> and that looks a bit like a UFO. The operator is another way of referring to the compareTo method of the Comparable interface. This means we can implement the compareTo method in our own classes and this will allow us to use the <=> operator in our code. And of course all classes which already have implemented the compareTo method can be used with the spaceship operator. The operator makes for good readable sort methods.

class Person implements Comparable {
    String username
    String email

    int compareTo(other) {
        this.username <=> other.username

assert -1 == ('a' <=> 'b')
assert 0 == (42 <=> 42)
assert -1 == (new Person([username:'mrhaki', email: '']) <=> new Person([username:'zavaria', email:'']))
assert [1, 2, 3, 4] == [4, 2, 1, 3].sort{ a, b -> a <=> b }

Run this script in GroovyConsole.