Thank you.
Let me try to explain in my own words what’s happening to validate my understanding:
-
bufferedconverts aReaderto aBufferedReaderif it isn’t still aBufferedReader. - The
BufferedReader(which implementsAutoCloseable) is then made available in theuseblock. - Inside
usethe passed functionblockreceives an instance of a sequence obtained from theBufferedReader.
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.