Will the foreach
method of a Scala immutable Queue always be processed in the order one expects for a queue or is there a method that guarantees the order? Or do I have to use a loop + dequeue
?
3
votes
1 Answers
6
votes
scala.collection.immutable.Queue
is scala.collection.Seq
. See Seq
documentation:
Sequences are special cases of iterable collections of class Iterable. Unlike iterables, sequences always have a defined order of elements.
So yes, you'll get the same elements order with foreach
and with loop + dequeue
.
If you don't trust documentation you could take a look at implementation:
Queue#foreach
is inherited from IterableLike
and implemented like this:
def foreach[U](f: A => U): Unit = iterator.foreach(f)
Queue#iterator
is implemented like this:
override def iterator: Iterator[A] = (out ::: in.reverse).iterator
And Queue#dequeue
returns the first element of out
, if any, or the last element of in
. So you'll get the same elements order.