Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Queue.foreach properly ordered?

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?

like image 830
Jens Schauder Avatar asked Mar 21 '23 08:03

Jens Schauder


1 Answers

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.

like image 105
senia Avatar answered Apr 02 '23 11:04

senia