(blog-of ‘Alex’)

A personal blog about software development and other things. All opinions expressed here are my own, unless explicitly stated.

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.