How to split iterator into head and tail

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

scala.io.Source.fromFile("somefile").getLines

What’s the correct way to do this?

I want to do something like
val (head,tail) = scala.io.Source.fromFile("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.

2 Likes

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

Side note: scala.io.Source 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
https://www.scala-lang.org/api/current/scala/util/Using$.html

    scala.util.Using.resource(scala.io.Source.fromFile("somefile")){
      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 Iterator.next()?