VOOZH about

URL: https://www.geeksforgeeks.org/scala/object-equality-in-scala/

⇱ Object Equality in Scala - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Object Equality in Scala

Last Updated : 29 Dec, 2022

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 : 

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 : 

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 == .

Comment
Article Tags:
Article Tags:

Explore