what is this operator called and what is it used for <=>
I recently came across this magical operator when digging into Groovy: <=>
Groovy has really made me happy with elvis operators ?. and ?: which I use constantly now and very much wish were in Java. With this new operator, I have only found this reference. It seems to make comparators much easier. My questi开发者_如何学运维on is how does it handle null values and how does it compare non Comparable object. Does this operator have a name, I couldn't find it Googling.
You got a list of operators here. It is called the "Spaceship" operator. It handles null without problem.
It's called the spaceship operator and is also commonly used for comparison in Ruby.
http://www.objectpartners.com/2010/02/08/the-groovy-spaceship-operator-explained/
Name : Spaceship operator
Method that it uses : a.compareTo(b) //where a and b are the variables that has been used
Class : java.lang.Comparable
And this link explains about that operator in a bit more . Click Here
Like many others mention, it's called the spaceship operator. Here's my test:
def a
def b
println 1 <=> 0 // 1
println 0 <=> 1 // -1
println 1 <=> a // 1
println b <=> 0 // -1
println a <=> b // 0
println "abc" <=> "def" // -1
println "abc" <=> 1 // throw exception: java.lang.ClassCastException
精彩评论