This post walks through how to use the == operator in Groovy and what to expect. Let’s start with an example.
This looks simple, and you can probably guess the output. Once executed, the actual output is:
Notice that == and equals() return different results — we expected true on lines 7 and 8 but got false. Why?
- Is there a bug in Groovy?
- Does
==callequals()?
Plenty of questions can come to mind. The real reason:
The implementation of
==in Groovy is slightly different from Java’s.
In Java, == means equality of primitive types or identity for objects.
In Groovy:
- If the operands are
Comparable,==translates toa.compareTo(b) == 0. - If they are not
Comparable,==translates toa.equals(b).
To check for identity in Groovy, use the is() method, e.g. a.is(b).
Hope this helps.