The guy who tries-with-resources with kotlin

Sudden conclusion

Unfortunately kotlin doesn't have try-with-resources itself. Instead, there is ʻuse` as an equivalent function (strictly speaking, extension function: extension function).

java


try (OutputStream ost = Files.newOutputStream(path)) {
    FileCopyUtils.copy(inst, ost);
} catch (Exception e) {
    e.printStackTrace();
}

This is ↓

kotlin


try {
    Files.newOutputStream(path).use { ost ->
        FileCopyUtils.copy(inst, ost)
    }
} catch (e: Exception) {
    e.printStackTrace()
}

It will be like this.

Personally, if the content of ʻuse is one line, it is often written without line breaks like Files.newOutputStream (path) .use {ost-> FileCopyUtils.copy (inst, ost)} `. I like kotlin because it can be written more clearly than java.

In case of multiple resources

If you want to use multiple resources, you can chain ʻuse`.

kotlin


try {
    Files.newOutputStream(path).use { ost ->
        Files.newInputStream(path).use { inst ->
            FileCopyUtils.copy(inst, ost)
        }
    }
} catch (e: Exception) {
    e.printStackTrace()
}

If you chain too much, the nest will be deeper.

reference

Recommended Posts

The guy who tries-with-resources with kotlin
The guy who replicates sessions with tomcat
The guy who can't handle errors in the stream
A crappy guy who makes layout adjustments sober and efficient with the development of libGDX
Find the number of days in a month with Kotlin
Change the port with SpringBoot
Mock the constructor with PowerMock
I read the Kotlin startbook
With the error Cordova-> Looper.prepare ()
Monitor the clipboard with JNA
I want to return to the previous screen with kotlin and java!