Try-with-resources: the Kotlin way?

Petr,

Thanks for such a detailed post! We are definitely looking into try-with-resource pattern but we don’t want to add special constructs to the language until absolutely necessary. So, we are experimenting with constructs like this:

val text = using {
  val is = InputStream(…).autoClose()
  val os = OutputStream(…).autoClose()
  “text”

}

using introduces “ResourceContext” and autoClose adds items into it. In finally block inside “using” it closes them in reverse order. So, if OutputStream throws, InputStream will still be destroyed.
there could be variants like this:

using(resource1, resource2) {} // when you already have resources

InputStream(…).using { stream -> … } // for a shorter syntax with one resource

This is being developed right now with the rest of IO part of stdlib, stay tuned!