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: 'test@email.com']) <=> new Person([username:'zavaria', email:'tester@email.com']))
assert [1, 2, 3, 4] == [4, 2, 1, 3].sort{ a, b -> a <=> b }
Run this script in GroovyConsole.
3 comments:
Very cool operator! Now I just need to remember that it's there.
I don't mean to be making a habit of this, but I think I noticed a typo in this post, too. Don't you mean "assert -1 == ..." for the Person object comparison?
Thanks,
Matt
@blog: Please keep noticing my typos. This time you're right again. I've copied the code and then changed it in Blogger. Shouldn't be doing that anymore ... ;-)
Traditionally, it wouldn't be because it resembles an UFO, it is because it is similar to a Star Wars TIE fighter.
Post a Comment