编辑本页

作用域内资源用法

Kotlin does not have Python's resource managers or Java's try-with-resources, but thanks to extension functions, there's use:

File("/home/aasmund/test.txt").inputStream().use {
     val bytes = it.readBytes()
     println(bytes.size)
}

use can be invoked on anything that implements the Closeable interface, and when the use block ends (whether normally or due to an exception), close() will be called on the object upon which you invoked use. If an exception is raised within the block or by close(), it will bubble out of use. If both the block and close() raise, it's the exception from the block that will bubble out.

Thus, you can create something resource manager-like by creating a class that implements Closeable, does its setup work in init, and does its cleanup work in close().

In case you're wondering about how use, which is a function, can just be followed by a block like that, see the section on DSL support.


← 上一节:文件 I/O 下一节:编写文档 →

本资料英文原文的作者是 Aasmund Eldhuset;其所有权属于可汗学院(Khan Academy),授权许可为 CC BY-NC-SA 3.0 US(署名-非商业-相同方式共享)。请注意,这并不是可汗学院官方产品的一部分。中文版由灰蓝天际译,遵循相同授权方式。