Groovy overloads the ==
operator and maps it to the equals()
method. This is very different from Java, so when developers are switching back and forth between Groovy and Java mistakes are bound to happen. In Java we use the ==
operator to see if variables are referring to the same object instance. In Groovy we use the ==
operator to see if two objects are the same, in Java we would use the equals()
method for this. To test if two variables are referring to the same object instance in Groovy we use the is()
method. The !=
operator is also overloaded and maps to the !equals()
statement.
And because we are in Groovy land all null values are handled gracefully. We don't have to write extra checks to check for null values before we can test for equality.
Integer myInt = 42 Integer anotherInt = myInt Integer newInt = 42 Integer different = 101 assert myInt == anotherInt // In Java: myInt != null && myInt.equals(anotherInt) assert myInt.is(anotherInt) // In Java: myInt == anotherInt assert myInt == newInt assert myInt != different