Skip to content

Commit 41df0ec

Browse files
committed
Add example for using a custom class with Set
1 parent dfb5b04 commit 41df0ec

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

_overviews/scala3-book/collections-classes.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -864,7 +864,51 @@ val c = b -- Seq(3, 4) // HashSet(1, 2)
864864

865865
{% endtabs %}
866866

867+
## Using custom classes with Maps and Sets
867868

869+
To use a custom class with a Map or a Set, override its `equals` and `hashCode` methods. Objects that are equal according
870+
to the `equals` method must have identical hash codes, but objects with identical hash codes don't necessarily have to
871+
be equal.
872+
873+
{% tabs using-custom-classes class=tabs-scala-version %}
874+
875+
{% tab 'Scala 2' %}
876+
```scala
877+
class Pet(val name: String, val age: Int){
878+
override def equals(obj: Any): Boolean = {
879+
obj match {
880+
case that: Pet => that.name == this.name && that.age == this.age
881+
case _ => false
882+
}
883+
}
884+
override def hashCode(): Int = 41 * name.hashCode * age.hashCode
885+
override def toString: String = s"Pet($name, $age)"
886+
}
887+
val t = new Pet("Rex", 12)
888+
val t2 = new Pet("Rex", 12)
889+
val s = Set(t, t)
890+
println(s) // Set(Pet(Rex, 6))
891+
```
892+
{% endtab %}
893+
894+
{% tab 'Scala 3' %}
895+
```scala
896+
class Pet(val name: String, val age: Int):
897+
override def equals(obj: Any): Boolean =
898+
obj match
899+
case that: Pet => that.name == this.name && that.age == this.age
900+
case _ => false
901+
override def hashCode(): Int = 41 * name.hashCode * age.hashCode
902+
override def toString: String = s"Pet($name, $age)"
903+
904+
val p1 = new Pet("Rex", 6)
905+
val p2 = new Pet("Rex", 6)
906+
val s = Set(t, t)
907+
println(s) // Set(Pet(Rex, 6))
908+
```
909+
{% endtab %}
910+
911+
{% endtabs %}
868912

869913
## Range
870914

0 commit comments

Comments
 (0)