I want to write a Scala function to read all of the lines from a file lazily (i.e returning an Iterator[String]
) which also closes the file afterwards. I know about the idiom io.Source.fromFile("something.txt").getLines
however as noted here this will not close the file afterwards. Surely there is a simple way to do this?
Currently I'm using this, with the scala-arm library:
import resource.managed
import io.{Source, BufferedSource}
def lines(filename: String): Iterator[String] = {
val reader = managed(Source.fromFile(filename, "UTF-8"))
reader.map(_.getLines).toTraversable.toIterator
}
but this seems to read the whole file into memory as far as I can tell.
I come from a Python background, where this is laughably trivial:
def lines(filename):
with open(filename) as f:
for line in f:
yield line
Surely there is a reasonably straightforward Scala equivalent which I just haven't managed to work out yet.