It's often times convenient that Groovy maps == to equals() but what do I do when I want to compare by identity? For example, GPathResult implements equals by calling text(), which is empty for most internal nodes. I'm trying to identify the root node but with that implementation it's not possible. It would be possible if I could compare by identity.
== is symmetric in groovy. While that table is super handy, it's a bit misleading as == isn't actually on it.
== operator is used to check whether two variables reference objects with the same value.
Thankfully, a different portion of the Groovy Language Documentation saves the day: Behaviour of == In Java == means equality of primitive types or identity for objects. In Groovy == translates to a. compareTo(b)==0, if they are Comparable, and a. equals(b) otherwise.
You use the is
method. ie:
a.is( b )
See the docs for more description
Since groovy 3, you can use ===
(or !==
for the opposite)
Use is
for testing object identity:
groovy:000> class Foo { }
===> true
groovy:000> f = new Foo()
===> Foo@64e464e4
groovy:000> g = new Foo()
===> Foo@47524752
groovy:000> f.is(g)
===> false
groovy:000> g.is(f)
===> false
groovy:000> f.is(f)
===> true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With