![]() |
VOOZH | about |
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 -
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
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 == .