How to split iterator into head and tail

getLines returns an iterator which I want to split into head and tail."somefile").getLines

What’s the correct way to do this?

I want to do something like
val (head,tail) ="somefile").getLines().splitAt(1)
But there doesn’t seem to be any such function.

Iterator is not a real collection. It defines next and hasNext and invoking next mutates it. If you want head then go for BufferedIterator or convert the iterator to a real sequence that remembers elements.


You can transfer Iterator to any collection first.
For example:
val (head, tail) ="somefile").getLines.toArray.splitAt(1)

Side note: needs closing, otherwise you could run out of file handles (on any OS) and on Windows keeping the file open means it cannot be deleted.

1 Like

Thanks for reminding. Then we can use scala.util.Using$.html

      src => {
        val lines = src.getLines().toArray
        val (head, tail) = lines.splitAt(1)
        println(head, tail)
1 Like

Do you want the first element and an iterator with the remaining elements? How about