What is the recommended way to encapsulate an itera{tor/ble} and it's potential closeable?


#1

I often find myself creating a small case class that holds both an Iterator and a corresponding Closeable (say if the Iterator comes from streaming a file). Is there a commonly used class for this somewhere? Maybe even a monad, to make function composition easier?

Thanks!


#2

geny.Generators help you do this, in your specific using the selfClosing constructor:

def getFileLines(path: String): geny.Generator[String] = Generator.selfClosing{
  val s = scala.io.Source.fromFile(path)(charSet)
  (s.getLines(), () => s.close())
}

#3

Interesting, turns out you had created a project matching my question specifically!

Well thanks for that :slight_smile:


#4

It happens more often than you might think :sweat_smile: