4.15. Defining an equals Method (Object Equality)
Problem
You want to define an equals
method for your class so you can compare object instances to each
other.
Solution
Like Java, you define an equals
method (and hashCode method) in your
class to compare two instances, but unlike Java, you then use the
== method to compare the equality of
two instances.
There are many ways to write equals methods. The following example shows
one possible way to define an equals
method and its corresponding hashCode
method:
classPerson(name:String,age:Int){defcanEqual(a:Any)=a.isInstanceOf[Person]overridedefequals(that:Any):Boolean=thatmatch{casethat:Person=>that.canEqual(this)&&this.hashCode==that.hashCodecase_=>false}overridedefhashCode:Int={valprime=31varresult=1result=prime*result+age;result=prime*result+(if(name==null)0elsename.hashCode)returnresult}}
This example shows a modified version of a hashCode method that Eclipse generated for a
similar Java class. It also uses a canEqual method, which will be explained
shortly.
With the equals method defined,
you can compare instances of a Person
with ==, as demonstrated in the
following tests:
importorg.scalatest.FunSuiteclassPersonTestsextendsFunSuite{// these first two instances should be equalvalnimoy=newPerson("Leonard Nimoy",82)valnimoy2=newPerson("Leonard Nimoy",82)valshatner=newPerson("William Shatner",82)valed=newPerson("Ed Chigliak",20)// all tests ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access