Scala | Equals
Last Updated :
13 May, 2019
Equals is a trait, which is a linking that accommodates functionalities of equality. It extends the class Any. The Linear Supertype here is Any and the Subclasses here are Product, Product1, Product2, and many more.
Abstract value members
The abstract value member here is:
abstract def canEqual(that: Any): Boolean
It returns true if the stated instances are equal.
Example :
case class Employee (name : String, age : Int)
object Main
{
def main(args : Array[String])
{
var c = Employee( "Nidhi" , 23 )
var d = Employee( "Nidhi" , 23 )
var e = Employee( "Nidhi" , 25 )
println(c.canEqual(d))
println(c.canEqual(e))
}
}
|
Here, we have used canEqual method for proving the equality of the instances.
Example :
case class Name (firstname : String, lastname : String)
object Main
{
def main(args : Array[String])
{
var x = Name( "Nidhi" , "Singh" )
var y = Name( "Nidhi" , "Singh" )
var z = Name( "Geeta" , "Sharma" )
println(x.equals(y))
println(x.equals(z))
println(y == z)
}
}
|
Here, we have used method equals and == for checking the equality.
Share your thoughts in the comments
Please Login to comment...