11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

kotlinでtry-with-resourcesするやつ

Posted at

いきなり結論

残念ながらkotlinにはtry-with-resourcesそのものはないです。
その代わり、同等のfunction(厳密にはextension function: 拡張関数)としてuseがあります。

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

これが↓

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

こうなります。

個人的にはuseの中身が1行であればFiles.newOutputStream(path).use { ost -> FileCopyUtils.copy(inst, ost) }みたいに改行せずに書くことが多いです。
kotlinはjavaに比べてスッキリと書けるのところが好きなので。

複数resourceの場合

複数のresourceを使いたい場合はuseをchainできます。

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

あまりchainしすぎるとネストが深くなるのが玉に瑕。

参考

11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?