dromodel
dromodel

Reputation: 10213

How can I perform a reference equals in 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.

Upvotes: 42

Views: 6783

Answers (2)

tim_yates
tim_yates

Reputation: 171124

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)

Upvotes: 50

Nathan Hughes
Nathan Hughes

Reputation: 96414

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

Upvotes: 10

Related Questions