Consider the following sketch for using a loop to empty a queue in Scala:
var queue = immutable.Queue[T]( /* .. some content ..*/ )
while( !queue.isEmpty ) {
val (record, tempQueue) = queue.dequeue
queue = tempQueue
doSomethingWith(record)
}
Is there any trick to avoid the temporary variable tempQueue and get Scala to assign the returned Queue value directly to the loop variable queue? Having to introduce the extra symbol is annoying, plus presumably there may be some superfluous copying (although this might get optimized away, not sure).
Edit 1: of course, as Ionut G. Stan points out, I can skip the pattern matching and take apart the returned pair myself, as in:
while( !queue.isEmpty ) {
val pair = queue.dequeue
queue = pair._2
doSomethingWith(pair._1)
}
So I should refine the question as follows: is there any way to use the syntactic sugar of pattern matching to do this more elegantly? I was hoping for something like this, which unfortunately does not compile:
var queue = immutable.Queue[T]( /* .. some content ..*/ )
var record : A = _
while( !queue.isEmpty ) {
(record, queue) = queue.dequeue
doSomethingWith(record)
}
If you insist on keeping that structure (the
whileloop, etc.), I don’t see how you can make it shorter, except perhaps:Since you’re using an immutable queue, however, the simplest equivalent code is probably:
See also this related question which confirms there is no way to assign to a pre-existing
varwith pattern-matching notation.The Scala Language Specification, Section 4.1, is also clear: pattern-matching-style assignments expand into
valdefinitions, i.e. they will bind a new identifier.