Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using custom classes with Maps and Sets #3108

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions _overviews/scala3-book/collections-classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -864,7 +864,51 @@ val c = b -- Seq(3, 4) // HashSet(1, 2)

{% endtabs %}

## Using custom classes with Maps and Sets

To use a custom class with a Map or a Set, override its `equals` and `hashCode` methods. Objects that are equal according
to the `equals` method must have identical hash codes, but objects with identical hash codes don't necessarily have to
be equal.

{% tabs using-custom-classes class=tabs-scala-version %}

{% tab 'Scala 2' %}
```scala
class Pet(val name: String, val age: Int){
override def equals(obj: Any): Boolean = {
obj match {
case that: Pet => that.name == this.name && that.age == this.age
case _ => false
}
}
override def hashCode(): Int = 41 * name.hashCode * age.hashCode
override def toString: String = s"Pet($name, $age)"
}
val t = new Pet("Rex", 12)
val t2 = new Pet("Rex", 12)
val s = Set(t, t)
println(s) // Set(Pet(Rex, 6))
```
{% endtab %}

{% tab 'Scala 3' %}
```scala
class Pet(val name: String, val age: Int):
override def equals(obj: Any): Boolean =
obj match
case that: Pet => that.name == this.name && that.age == this.age
case _ => false
override def hashCode(): Int = 41 * name.hashCode * age.hashCode
override def toString: String = s"Pet($name, $age)"

val p1 = new Pet("Rex", 6)
val p2 = new Pet("Rex", 6)
val s = Set(t, t)
println(s) // Set(Pet(Rex, 6))
```
{% endtab %}

{% endtabs %}

## Range

Expand Down
Loading