How to Override equals Method in Scala

Overriding equals Method in Scala

Hello everyone, In this post, We will show you, How to override equals method in Scala programming language. The sample program has been tested and posted in the same post.

Employee Class (Emploee.scala)

The below Employee class, which is overriding the equals() method and returning boolean value based on the conditions.

Note: When you override the any super class method in scala. We should use override keyword before the method (ie: override def equals())

 
package com.dineshkrish.scala

class Employee(empId: Int, empName: String) {

  def getEmpId(): Int = {

    return empId;
  }

  def getEmpName(): String = {

    return empName;
  }

  override def equals(obj: Any): Boolean = {

    // type casting to Employee
    var employee = obj.asInstanceOf[Employee];

    if (employee.getEmpId() == empId) {

      return true;
    }

    return false;
  }

}

Main Class (Test.scala)

package com.dineshkrish.scala

object Test {

  def main(args: Array[String]): Unit = {

    var employee1 = new Employee(101, "Dinesh Krishnan");

    var employee2 = new Employee(101, "Dinesh Krishnan");
    
    var employee3 = new Employee(102, "Dinesh Krishnan");

    // comparing 1 and 2
    if (employee1.equals(employee2)) {

      println("Equal");
      
    } else {

      print("Not Equal");
      
    }
    
    // comparing 1 and 3
    if (employee1.equals(employee3)) {

      println("Equal");
      
    } else {

      print("Not Equal");
      
    }
  }
}

Output

Equal
Not Equal

References

1. Scala Programming Language
2. Scala Language Documentation
3. Overriding toString() method

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.