kotlintry-with-resources

Try-with-resources in Kotlin


When I tried to write an equivalent of a Java try-with-resources statement 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 include such a construct, but maybe I'm missing something. It defines the grammar for a try block as follows:

try : "try" block catchBlock* finallyBlock?;

Solution

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

    How to use it:

    OutputStreamWriter(r.getOutputStream()).use {
        // `it` is your OutputStreamWriter
        it.write('a')
    }