<=>
.When you use this operator for 2 values
a <=> b
, Groovy translates this to code something like that a.compareTo(b)
. Well that's not the true, as it also can handle null
values correctly. So you wouldn't get NPE
, when you compare value with null
or vice versa. For instance, next script:outputs
a.compareTo(b) = -1
a.compareTo(a) = 0
b.compareTo(b) = 0
where we can see, that
null
values are handled correctly, without any runtime exceptions.With such operator we could write really nice and simple code to allow multiple comparisons for object values.
Lets we have a class
Person
with firstName, lastName and age data:And we need to sort a list of Persons by age, than by name (first by last name, than by first name). Assume, this is standard sorting mode, so we may prefer to implement
Comparable
interface:Method
compareTo()
isn't implemented yet. So lets try to implement in Java first. It would look something like this:Hm... Looks ugly! Too much
if
's, too much checks, too much 0, 1 and -1. Hard to see the logic behind the code ((.And here how this can be written with Groovy's
<=>
operator:And a simple test:
prints
john <=> mark = -1
As for me, it looks wonderful.
No comments:
Post a Comment