Skip to content

Default implementation of immutable.Set has non-deterministic iteration order #8184

@scabug

Description

@scabug

Run the following code in the Scala REPL:

val o1 = new Object()
val o2 = new Object()
val o3 = new Object()
val o4 = new Object()
val o5 = new Object()
val items = Set(o1, o2, o3, o4, o5)
items.foreach(println)

Observe that the order the items are printed is not the order they were inserted into the set constructor. Further observe that the order is not consistent across multiple invocations of the REPL (i.e. different JVM runs).

This non-deterministic ordering can make bugs harder to reproduce and can lead to confusion if it impacts user-visible output or behaviour. It's also easy to miss this when writing tests, since sets of size < 5 are special implementations Set1...Set4 which do have deterministic iteration order.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions