# Why doesn't Sequence implement AutoCloseable?

**URL:** <https://discuss.kotlinlang.org/t/why-doesnt-sequence-implement-autocloseable/19072>\
**Category:** Uncategorized\
**Created:** [September 7, 2020, 11:56am UTC](https://discuss.kotlinlang.org/t/why-doesnt-sequence-implement-autocloseable/19072 "2020-09-07T11:56:46Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![medium](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/medium/32/10404_2.png) [@medium](https://discuss.kotlinlang.org/u/medium)\
**Post date:** [September 7, 2020, 1:47pm UTC](https://discuss.kotlinlang.org/t/why-doesnt-sequence-implement-autocloseable/19072/5 "2020-09-07T13:47:58Z")

</div>

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](https://discuss.kotlinlang.org/t/splitting-sequence-in-chunks-based-on-predicate/19005) 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.

---

_[View the full topic](https://discuss.kotlinlang.org/t/why-doesnt-sequence-implement-autocloseable/19072)._
