# Kotlin needs try-with-resources

**URL:** <https://discuss.kotlinlang.org/t/kotlin-needs-try-with-resources/214>\
**Category:** Language Design\
**Created:** [July 5, 2015, 12:32am UTC](https://discuss.kotlinlang.org/t/kotlin-needs-try-with-resources/214 "2015-07-05T00:32:25Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![orangy](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/orangy/32/1462_2.png) [@orangy](https://discuss.kotlinlang.org/u/orangy)\
**Post date:** [July 5, 2015, 10:15am UTC](https://discuss.kotlinlang.org/t/kotlin-needs-try-with-resources/214/2 "2015-07-05T10:15:42Z")

</div>

Absolutely agree. But we want to avoid language construct just for this as much as possible and we have an idea of the solution, it's not implemented in stdlib yet, but you can try it using code like this:

&nbsp;

```kotlin
class ResourceHolder : AutoCloseable {
    val resources = arrayListOf<AutoCloseable>()
  fun <T : AutoCloseable> T.autoClose(): T {
  resources.add(this)
  return this
    }
  override fun close() {
  resources.reverse().forEach { it.close() }
    }
}
 
fun <R> using(block: ResourceHolder.() -> R): R {
  val holder = ResourceHolder()
  try {
  return holder.block()
  } finally {
  holder.close()
  }
}

 
fun copy(from: Path, to: Path) {
using {
 val input = Files.newInputStream(from).autoClose()
val output = Files.newOutputStream(to).autoClose()
input.copyTo(output)
}
}
```

`
Of course, it’s not production ready code, it’s just to demonstrate an idea. E.g. "close() in holder’s code should handle exceptions, etc. `

---

_[View the full topic](https://discuss.kotlinlang.org/t/kotlin-needs-try-with-resources/214)._
