众所周知,在java中,在finally代码块中可以使用close()关闭不使用的stream。当然kotlin也可以沿用这种操作,那是否有更简单的操作呢?答案是肯定的。
Closeable.use,只要继承了Closeable的类,都可以使用。通过看use的源码,可以看到最后会调用close方法。
因此只需要这样使用:
BufferedWriter(OutputStreamWriter(out)).use {
it.write(inputText)
}
把需要执行的动作放在block中,执行完后,自动会关闭BufferedWriter的流
参考:
1.https://stackoverflow.com/questions/46098105/is-there-a-way-to-open-and-close-a-stream-easily-at-kotlin/46098204?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
2.https://stackoverflow.com/questions/26969800/try-with-resources-in-kotlin
本文介绍Kotlin中如何利用Closeable.use方法简化资源管理,通过内置的use函数自动关闭资源,避免显式调用close方法。这种方式不仅提高了代码的简洁性,也增强了程序的安全性和可靠性。
1807

被折叠的 条评论
为什么被折叠?



