Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy == operator

Tags:

Until now, my understanding was that == is an operator overload for .equals(). However, I recently discovered that

new Integer(1) == new Long(1) // returns true 

whereas

new Integer(1).equals(new Long(1)) // returns false 

so I guess == is not exactly a shorthand for .equals(), so how does it determine equality?

like image 569
Dónal Avatar asked Dec 03 '12 16:12

Dónal


People also ask

What is == in Groovy?

In Groovy == translates to a. compareTo(b)==0, if they are Comparable, and a. equals(b) otherwise.

What does operator mean in Groovy?

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Groovy has the following types of operators − Arithmetic operators. Relational operators. Logical operators.

Does Groovy have operator?

Groovy offers three logical operators for boolean expressions: && : logical "and" || : logical "or" ! : logical "not"


1 Answers

== in Groovy is roughly equivalent to equals(), however, you'll find it's different from Java when comparing different classes with the same value - if the class is Comparable. Groovy also does type casting if possible.

If you check out the code, it looks like ultimately compareToWithEqualityCheck() is executed for ==.

like image 124
doelleri Avatar answered Jan 17 '23 18:01

doelleri