Reputation: 662
I want to prepend a new iterator to my existing iterator.
How can I prepend a new Iterator to an existing Iterator?
Why does my code cause my REPL to hang?
The following hangs indefinitely in my REPL:
scala> var i = Seq(1).iterator
var i: Iterator[Int] = <iterator>
scala> i = Seq(2).iterator ++ i
// mutated i
scala> i.next()
val res0: Int = 2
scala> i.next()
. . .
Note that the following works, but this is an append not a prepend:
var i = Seq(1).iterator
i = i ++ Seq(2).iterator
i.next()
i.next()
This also works, but materializes the entire iterator which I cannot do:
var i = Seq(1).iterator
i = (Seq(2) ++ i.toSeq).iterator
i.next()
i.next()
Thanks!
Upvotes: 0
Views: 90
Reputation: 2500
Simply speaking, it hangs because you have there an infinite loop. In the line where you think you are merging iterators, you are actually referencing the new i
(laziness) and not the initial value of i
.
You can get over that by introducing a new var as Luis Miguel pointed out
var i = Seq(1).iterator
var j = i
i = Seq(2).iterator ++ j
i.next()
i.next()
so that should do the trick. Hope it helps and is clear enough.
Upvotes: 1