Scala | Equals

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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of trait 
// Equals
  
// Creating a case class of 
// employee
case class Employee (name:String, age:Int) 
  
// Creating object
object Main 
    // Main method 
    def main(args: Array[String]) 
    
        // Creating objects
        var c = Employee("Nidhi", 23
        var d = Employee("Nidhi", 23)
        var e = Employee("Nidhi", 25)
              
        // Displays true if instances 
        // are equal else false
        println(c.canEqual(d))
        println(c.canEqual(e))
          
    

chevron_right


Output:

true
true

Here, we have used canEqual method for proving the equality of the instances.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of trait 
// Equals
  
// Creating a case class of 
// Name
case class Name (firstname:String, lastname:String) 
  
// Creating object
object Main 
    // Main method 
    def main(args: Array[String]) 
    
        // Creating objects
        var x = Name("Nidhi", "Singh"
        var y = Name("Nidhi", "Singh")
        var z = Name("Geeta", "Sharma")
              
        // Displays true if instances 
        // are equal else false
        println(x.equals(y))
        println(x.equals(z))
        println(y==z)
          
    

chevron_right


Output:

true
false
false

Here, we have used method equals and == for checking the equality.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.