Closable Sequence

A reoccuring problem with Iterators and sequences is that they could use underlying resources which need to be closed.

Would it be possible to factor all terminal operations in Sequences.kt into an interface which can be overriden by custom sequences, to call a method like “cleanup” inside a try / catch block?

1 Like

The problem is how to ensure that the cleanup code is called. I can see three approaches to this:

  • Use scope based cleanup the way that use works. This means that further processing of the sequence would be nested in the scope that cleans up at the end.
  • Use a monad where the initialization of the resource is delayed to the execution of the body (otherwise it is the same as the use clause)
  • Somehow register resources as needing closing in an enclosing scope that autocloses them. This is technically difficult and not that more elegant/usable than the use approach.