Why doesn't Sequence implement AutoCloseable?

Thank you.

Let me try to explain in my own words what’s happening to validate my understanding:

  1. buffered converts a Reader to a BufferedReader if it isn’t still a BufferedReader.
  2. The BufferedReader (which implements AutoCloseable) is then made available in the use block.
  3. Inside use the passed function block receives an instance of a sequence obtained from the BufferedReader.

Would that be the solution you had in your mind:

fun <Input, Output> Stream<Input>.useSequence(
    block: (Sequence<Input>) -> Sequence<Output>
): Sequence<Output> = 
    this.use { block(it.asSequence()) }

?

That wouldn’t be too bad, but it had the drawback, that I’d need to write all operations that should be performed on the closeable resource into one block. At the moment my repository function converts the Stream to a Sequence, applies a function for building chunks and then returns this decorated sequence for further use.

My idea was to make the (closeable) sequence available for the user and use use in the final destination where the terminal operation of the sequence happens, maybe with a class like this:

class CloseableSequence<T>(
    private val stream: Stream<T>
): Sequence<T> by stream.asSequence(), AutoCloseable by stream

But since all Sequence (extension) functions only work on the standard Sequence I’d need to cast before the use block containing the terminal operation – not a particular elegant solution.