Skip to content

Overriding productPrefix breaks case class hash code #13033

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

Closed
lrytz opened this issue Sep 10, 2024 · 1 comment · Fixed by scala/scala#11023
Closed

Overriding productPrefix breaks case class hash code #13033

lrytz opened this issue Sep 10, 2024 · 1 comment · Fixed by scala/scala#11023
Assignees
Labels
Milestone

Comments

@lrytz
Copy link
Member

lrytz commented Sep 10, 2024

Since scala/scala#7693

scala> abstract case class C1(a: Int)
     | class C2(a: Int) extends C1(a) { override def productPrefix = "C2" }
     | class C3(a: Int) extends C1(a) { override def productPrefix = "C3" }

scala> val s = collection.mutable.HashSet.empty[C1]

scala> s.addOne(new C2(1))

scala> val c3 = new C3(1)

scala> s.find(_ == c3)
val res1: Option[C1] = Some(C2(1))

scala> s.contains(c3)
val res2: Boolean = false
@som-snytt
Copy link

som-snytt commented Sep 10, 2024

Alternatively [instead of marking productPrefix with @deprecatedOverriding as originally suggested], canEqual is broken and should include productPrefix.

@SethTisue SethTisue added this to the 2.13.16 milestone Nov 6, 2024
@SethTisue SethTisue modified the milestones: 2.13.16, 2.13.17 Dec 13, 2024
lrytz added a commit to scala/scala3 that referenced this issue Apr 3, 2025
…22865)

Since 2.13, case class `hashCode` mixes in the hash code of the
`productPrefix` string. This is inconsistent with the `equals` method,
subclasses of case classes that override `productPrefix` compare equal
but have a different `hashCode`
(scala/bug#13033).

This commit changes `hashCode` to mix in the `productPrefix.hashCode`
statically instead of invoking `productPrefix` at runtime.

For case classes without primitive fields, the synthetic `hashCode`
invokes `ScalaRunTime._hashCode`, which mixes in the result of
`productPrefix`. To fix that, the synthetic hashCode is changed to
invoke `MurmurHash3.productHash` directly and mix in the name to the
seed statically.

Scala 3 forward port of scala/scala#11023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
3 participants