[Kotlin] Try resource, use {} block

In Java, when you write code in try(...), if exception throw, the resource will be closed automactially:

 

This is not necessary in Kotlin

fun printFile() {
    val input = FileInputStream("file.txt")
    input.use {
        // an exception can be thrown here
        // and input resource will be closed automaticlly
    }
}

 

posted @ 2020-10-30 01:39  Zhentiw  阅读(151)  评论(0编辑  收藏  举报