Closed winitzki closed 6 months ago
IMO this is a case where you need to increase the maximum stack size of the JVM to accommodate the depths in your workload.
It is not possible to implement hashCode()
for nested case classes without using the stack for the recursion.
Is there any way to avoid using Object#hashCode()
or to implement Map
and Set
in a different way?
You can box your keys in your own class that implements hashCode()
however you like.
When a data structure contains deeply nested case classes (at least 5000 levels deep) there is a stack overflow while computing
hashCode()
. The stack overflow happens inscala.util.hashing.MurmurHash3.productHash
.Because of this, deeply nested case classes cannot be used as keys in a
Map
or as elements of aSet
.Reproduction steps
Scala version: 2.12, 2.13, 3.3, 3.4
Run this program:
With other Scala versions, a stack overflow occurs at different nesting levels, but it always does occur.
Problem
A stack overflow occurs when putting a deeply nested data structure into a hashmap or into a set.
Expected behavior is that a data structure can be used as key of
Map
or as element ofSet
, regardless of nesting depth.Expected behavior is that
Object#hashCode()
does not throw exceptions regardless of the type of the object.