Open In App

Object Equality in Scala

Improve
Improve
Like Article
Like
Save
Share
Report

In programming language, Comparing two values for equality is ubiquitous. We define an equals method for a Scala class so we can compare object instances to each other. In Scala, equality method signifying object identity, however, it’s not used much. 
In scala, Three different equality methods available – 

  • The equals Method
  • The == and != Methods
  • The ne and eq Methods

Note: eq behave same as the == operator behaves in Java, C++, and C#, but not == in Ruby. The ne method is the negation of eq, i.e., it is equivalent to !(x eq y). In Java, C++, and C# the == operator tests for reference, not value equality. In contrast, Ruby’s == operator tests for value equality. But in Scala, == is testing for value equality.
Let’s understand with example.
Example : 

Scala




// Scala program of Equals
 
// Creating a case class of
// Subject
case class Subject (LanguageName:String, TopicName:String)
 
// Creating object
object GFG
{
    // Main method
    def main(args: Array[String])
    {
        // Creating objects
        var x = Subject("Scala", "Equality")
        var y = Subject("Scala", "Equality")
        var z = Subject("Java", "Array")
             
        // Displays true if instances
        // are equal else false
        println(x.equals(y))
        println(x.equals(z))
        println(y == z)
         
    }
}


Output: 

true
false
false
  • equals Method: The equals method used to tests value equality. if x equals y is true if both x and y have the same value. They do not need to refer to the identical instance. Hence, the equals method in Java and equals method in Scala behaves same.
  • The == and != Methods: While == is an operator in several languages, Scala reserved The == equality for the natural equality of every type. it’s a method in Scala, defined as final in Any. value equality will be tested by this. Here, x == y is true if both x and y have the same value.
  • ne and eq Methods: Reference equality will be tested by eq method. Here, x eq y is true if both x and y point to the same location in memory or x and y reference the same object. These methods are only defined for AnyRef.

If two object are equal according to the equals method, then calling the hash code method on each of the two objects must produce the same integer result. equals (and, ==) is by default the same as eq, but we can change its behavior by overriding the equals method in the classes we define. Scala treats == as if it were defined as follows in class Any: 
Below is the example of equals method and corresponding hashCode method:
Example : 

Scala




// Scala program to illustrate how
// hashCode() and equals() methods work
 
// Creating class
class Subject (name: String, article: Int)
{
    // Defining canEqual method
    def canEqual(a: Any) = a.isInstanceOf[Subject]
     
    // Defining equals method with override keyword
    override def equals(that: Any): Boolean =
        that match
    {
        case that: Subject => that.canEqual(this) &&
                    this.hashCode == that.hashCode
        case _ => false
    }
      
    // Defining hashcode method
    override def hashCode: Int = {
        val prime = 31
        var result = 1
        result = prime * result + article;
        result = prime * result +
                (if (name == null) 0 else name.hashCode)
        return result
    }
}
 
// Driver code
object GFG
{
    // Main method
    def main(args: Array[String])
    {
     
        // Creating the Objects of Geek class.
        // Subject g1 = new Subject("aa", 1);
        val g1 = new Subject("Scala", 28)
        val g2 = new Subject("Scala", 28);
         
         
        // Comparing above created Objects.
        if(g1.hashCode() == g2.hashCode())
        {
 
            if(g1.equals(g2))
                println("Both Objects are equal. ");
            else
                println("Both Objects are not equal. ");
     
        }
        else
            println("Both Objects are not equal. ");
    }
}


Output:  

Both Objects are equal. 

In above example, a modified version of a hashCode method that Eclipse generated for a similar Java class. It also uses a canEqual method. With the equals method defined, we can compare instances of a Subject with == .



Last Updated : 29 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads