Kotlin needs try-with-resources

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:

 
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.

5 Likes