Converting a Scala Iterator to a Vector

You can

Vector() ++ myIterator

which gives the correct thing with the correct type. For very small vectors and iterators, in high-performance loops, you may instead wish to

val b = Vector.newBuilder[WhateverType]
while (myIterator.hasNext) { b += myIterator.next }
b.result

which does the minimum work necessary (as far as I know) to create a vector. toIndexedSeq does essentially this, but returns a more generic type (so you're not actually guaranteed a Vector, even if it does return a Vector now.)


You can use _*, since all it does is pass a Seq with all the arguments. It will be inefficient, however, since it will first convert the iterator into a sequence, and then use that sequence to create another sequence.


You can use toIndexedSeq. It doesn't statically return a Vector, but it actually is one.

Tags:

Vector

Scala