3
0

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 3 years have passed since last update.

今日のことりん: try-with-resources

Last updated at Posted at 2020-05-24

Javaのtry-with-resourcesをご存知でしょうか。

try(InputStream inputStream = new FileInputStream("test")){
    // 処理
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

こんな感じでAutoClosableやClosableを実装しているクラスをtryの()で宣言すると自動的にclose()を呼び出してくれるような書き方のことです。

Kotlinではどうするか

実はKotlinではこの構文は使えません。書こうとするとコンパイルエラーになってしまいます。
そこでKotlinにはClosableには拡張関数 useが用意されていて、以下のように書くことができます。

try {
    FileInputStream("test").use {
        // 処理
    }
} catch (e: FileNotFoundException){
    e.printStackTrace()
} catch (e: IOException){
    e.printStackTrace()
}

なぜできるか?

useの中身をみてみるときちんとcloseされていることがわかります。
AutoClosable.ktClosable.ktで実装されています。

3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?