# Enum cases change hashcodes between runs

**URL:** <https://contributors.scala-lang.org/t/enum-cases-change-hashcodes-between-runs/7117>\
**Category:** Language Design\
**Created:** [May 4, 2025, 5:54pm UTC](https://contributors.scala-lang.org/t/enum-cases-change-hashcodes-between-runs/7117 "2025-05-04T17:54:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![soronpo](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/soronpo/32/533_2.png) [@soronpo](https://contributors.scala-lang.org/u/soronpo)\
**Post date:** [May 4, 2025, 5:54pm UTC](https://contributors.scala-lang.org/t/enum-cases-change-hashcodes-between-runs/7117/1 "2025-05-04T17:54:30Z")

</div>

I found that enum cases change hashcodes between runs unlike case objects that keep the same hashcodes.

> **[Scastie - An interactive playground for Scala.](https://scastie.scala-lang.org/gIcLuMBlTiSgyNuWzu2VTw)**
>
> enum Foo:
> case Bar, Baz
> 
> case object Bar2
> println(Foo.Bar.hashCode())
> println(Bar2.hashCode())

```scala
enum Foo:
  case Bar, Baz

case object Bar2
println(Foo.Bar.hashCode()) //changes value each run
println(Bar2.hashCode()) //stable value each run

```

I didn’t see this behavior documented anywhere and is quite unexpected.  
Is this an expected change derived from how enums are built or a bug?

Workaround:

```scala
trait StableEnum extends scala.reflect.Enum:
  override def hashCode: Int =
    if (this.getClass.isAnonymousClass())
      // uses both the enum class name and
      // the case enum to get a unique and stable hash
      (this.getClass.getName, this.ordinal).hashCode()
    else
      (this.getClass.getName, this.productIterator.toList).hashCode()

enum Foo extends StableEnum:
  case Bar, Baz
  case Gogo(arg: Int)

println(Foo.Bar.hashCode)
println(Foo.Gogo(1).hashCode)
println(Foo.Gogo(2).hashCode)

```

---

<div class="post-metadata">

**Author:** ![bishabosha](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/bishabosha/32/3101_2.png) [@bishabosha](https://contributors.scala-lang.org/u/bishabosha)\
**Post date:** [May 5, 2025, 8:27am UTC](https://contributors.scala-lang.org/t/enum-cases-change-hashcodes-between-runs/7117/3 "2025-05-05T08:27:45Z")

</div>

> <https://github.com/scala/scala3/issues/19177>
>
> \## Compiler version
> 3.3.1
> 
> \## Minimized code
> \`\`\`Scala
> enum Test:
> case A
> …
> 
> Test.A.hashCode
> \`\`\`
> \[Scastie\](https://scastie.scala-lang.org/CS6WjEKARlGxNvMULyTJEg)
> 
> \## Output
> The outputted value changes for each run. Most likely the hashCode is being computed from the memory position.
> 
> \## Expectation
> The hashCode should be stable across multiple JVMs.
