java中有个很好用的语法Try-with-resources
kotlin中有没有类似的呢?
当然有啊!
在kotlin stdlib包中有个use方法,用法如下:
OutputStreamWriter(r.getOutputStream()).use {
// by `it` value you can get your OutputStreamWriter
it.write('a')
}
几乎就是增加close功能的作用域函数let。
use的实现如下:
@InlineOnly
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
this?.close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
this?.close()
}
}
}