Close

Groovy Operators - Identity Operator

[Last Updated: Jan 23, 2019]

In groovy == does the same thing what equals() method does, i.e. it checks the equality based on the equals() method implementation. To check object reference equality we can use is() method.

src/Example1IdentityOperator.groovy

def num1 = new BigDecimal(12);
def num2 = new BigDecimal(12);
println num1 == num2
println num1.equals(num2)
println num1.is(num2)
println num1.is(num1)

Output

true
true
false
true

The method is() can also be used with our own objects:

src/Example2IdentityOperator.groovy

class MyClass {
    int num;

    MyClass(int num) {
        this.num = num
    }

    @Override
    boolean equals(Object obj) {
        return obj == null ? false : obj.num == this.num;
    }
}

def myClass1 = new MyClass(1);
def myClass2 = new MyClass(1);

println  myClass1==myClass2
println myClass1.equals(myClass2)
println myClass1.is(myClass2)

Output

true
true
false

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.5
  • JDK 9.0.1
Groovy - Identity Operator Select All Download
  • groovy-identity-operator
    • src
      • Example1IdentityOperator.groovy

    See Also