We often use the equality operators in programming to compare defined values. In Scala, we can perform the equality operation in three different ways:
Using the equals
method. The method equals
is used to test the value equality. It returns True
if the values being compared are same. Otherwise, it returns False
.
Using ==
and !=
operators. The operator ==
is the same as equals
method. It is also used to compare the equality of values. The operator ==
returns True
if both the values being compared are the same, and returns False
otherwise. The operator !=
works in the opposite way and is referred to as “not equal”. The operator !=
returns True
if both the values being compared are not the same. It returns False
otherwise.
==
is the same as.equals
.
ne
and eq
methods to compare the addresses of two values. These methods are used to compare the reference locality of the passed values. The method eq
returns True
if both the addresses containing the compared values are same, and it returns False
otherwise. The method ne
works in the complete opposite way, as it ne
returns True
if both the addresses containing the compared values are not the same and False
otherwise.Operator/Method | Description |
Equals | Method. Returns True if two values are equal |
== | Operator. Returns True if two values are equal |
!= | Operator. Returns True if two values are not equal |
ne | Method. Returns True if two values have different memory locations |
eq | Method. Returns True if two values have the same memory location |
object Main extends App {var x = Set("Hello", "World")var y = Set("Hello", "World")var z = Set("Hello", "xyz")// Displays true if instances// are equal else false// should be trueprintln(x.equals(y))// should be falseprintln(x.equals(z))// should be falseprintln(y == z)// should be trueprintln(x == y)// should be trueprintln(x!=z)// should be False as memory location for// x and y and z is differentprintln(x eq y)println( x ne y)println (y ne z)}
Free Resources