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.
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.
Recommended Posts