(blog-of ‘Alex’)

My blog about software development and other things

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:

Is an equivalent of the following:

try (final OutputStreamWriter it = new OutputStreamWriter(myOutputStream)) {

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