Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I perform a reference equals in Groovy?

Tags:

groovy

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.

like image 462
dromodel Avatar asked May 02 '12 15:05

dromodel


People also ask

Does == work in groovy?

== is symmetric in groovy. While that table is super handy, it's a bit misleading as == isn't actually on it.

Does == check for reference?

== operator is used to check whether two variables reference objects with the same value.

What does == mean in groovy?

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.


2 Answers

You use the is method. ie:

a.is( b )

See the docs for more description

edit

Since groovy 3, you can use === (or !== for the opposite)

like image 195
tim_yates Avatar answered Oct 25 '22 12:10

tim_yates


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
like image 39
Nathan Hughes Avatar answered Oct 25 '22 11:10

Nathan Hughes