When scala.collection.TraversableLike#head may returns different results in scala?

39 Views Asked by At

here is quote from documentation:

elects the first element of this traversable collection. Note: might return different results for different runs, unless the underlying collection type is ordered. Returns: the first element of this traversable collection. Throws: NoSuchElementException – if the traversable collection is empty.

Looks very strange. When can it return different results? Is it safe to call myMap.head twice?

1

There are 1 best solutions below

0
Gastón Schabas On

Not sure which version of scala are you using. After scala 2.12, that trait was removed.

The most important changes in the Scala 2.13 collections library are:

  • The type hierarchy is simplified. Traversable no longer exists, only Iterable.

The doc MUTABLE AND IMMUTABLE COLLECTIONS 2.8 - 2.12 might help you.

The following figure shows all collections in package scala.collection. These are all high-level abstract classes or traits, which generally have mutable as well as immutable implementations.

scala collection diagram

Traversable is an abstraction that provides an interface. Then you have the concrete implementation where not all of them keep the order. Once the collection is built, you can ask for the first element using the head method (remember that this one can throw an exception if the collection is empty, meanwhile headOption will always return a value). If you ask for the first element more than once to an immutable collection, it will return always the same value. In a mutable collection it's not always true.

The doc of that method says

Selects the first element of this traversable collection.

Note: might return different results for different runs, unless the underlying collection type is ordered.

Returns: the first element of this traversable collection. Throws: NoSuchElementException – if the traversable collection is empty.

When it says "might return different results for different runs" means that if you run the app two times, the result could be different in each exceution if the underlying collection is not ordered