JetBrains/rd库具有Lifetime
的概念,可以将其视为AutoCloseable
或IDisposeable
的反向版本(请参阅here和{{3 }}了解更多信息。
最简单的用例示例如下:
import com.jetbrains.rider.util.lifetime.Lifetime
import com.jetbrains.rider.util.lifetime.onTermination
import java.io.FileInputStream
import java.io.InputStream
class LifetimeExample(lifetime: Lifetime, private val input: InputStream) {
init {
lifetime.onTermination {
input.close()
println("File closed.")
}
}
fun process() {
println("${input.bufferedReader().readText().length} char(s) read.")
}
companion object {
@JvmStatic
fun main(vararg args: String) {
Lifetime.using {
LifetimeExample(it, FileInputStream("/etc/passwd")).process()
}
}
}
}