# Closable Sequence

**URL:** https://discuss.kotlinlang.org/t/closable-sequence/5280
**Category:** Language Design
**Created:** [November 6, 2017, 9:59am UTC](https://discuss.kotlinlang.org/t/closable-sequence/5280 "2017-11-06T09:59:18Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![fab1an](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/fab1an/32/1934_2.png) [@fab1an](https://discuss.kotlinlang.org/u/fab1an)
#### Post date: [November 6, 2017, 9:59am UTC](https://discuss.kotlinlang.org/t/closable-sequence/5280/1 "2017-11-06T09:59:18Z")

</div>

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

- [https://github.com/Kotlin/kotlin-coroutines/issues/10](https://github.com/Kotlin/kotlin-coroutines/issues/10)
- [https://youtrack.jetbrains.com/issue/KT-18961](https://youtrack.jetbrains.com/issue/KT-18961)
- [coroutines-examples/kotlin-coroutines-informal.md at master · Kotlin/coroutines-examples · GitHub](https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md#resource-management-and-gc)

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?

---

<div class="post-metadata">

### Author: ![pdvrieze](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/pdvrieze/32/1882_2.png) [@pdvrieze](https://discuss.kotlinlang.org/u/pdvrieze)
#### Post date: [November 7, 2017, 9:50am UTC](https://discuss.kotlinlang.org/t/closable-sequence/5280/2 "2017-11-07T09:50:41Z")

</div>

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.
