Try-with-resources in Kotlin

Alex picture Alex · Nov 17, 2014 · Viewed 27.8k times · Source

When I tried to write an equivalent of a Java try-with-resources code in Kotlin, it didn't work for me.

I tried different variations of the following:

try (writer = OutputStreamWriter(r.getOutputStream())) {
    // ...
}

But neither works.

Does anyone know what should be used instead? Apparently Kotlin grammar doesn't have definition for such a construct, but maybe I'm missing something. It defines grammar for try block as follows:

try : "try" block catchBlock* finallyBlock?;

Answer

user2235698 picture user2235698 · Nov 17, 2014

There is use-function in kotlin stdlib (src).

How to use it:

OutputStreamWriter(r.getOutputStream()).use {
    // by `it` value you can get your OutputStreamWriter
    it.write('a')
}