Try-with resources in Kotlin

If you’re familiar with Java but not that familiar with Kotlin you might have some difficulties with using standard control structures such as try-with resources.

In Kotlin it is also doable but it looks trickier, for example this code

OutputStreamWriter(myOutputStream).use {
    // you can reference `it` value which is a resource you're working on in this lambda:
    it.write('a')
}

Is an equivalent of the following:

try (final OutputStreamWriter it = new OutputStreamWriter(myOutputStream)) {
    it.write('a');
}

It is interesting that even though Kotlin uses lambda construction it doesn’t introduce any overhead – this code is inlined by Kotlin compiler.

Leave a Reply

Your email address will not be published. Required fields are marked *