在 Kotlin 中尝试资源 [英] Try-with-resources in Kotlin
本文介绍了在 Kotlin 中尝试资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试在 Kotlin 中编写 Java try
-with-resources 代码的等效代码时,它对我不起作用.
When I tried to write an equivalent of a Java try
-with-resources code in Kotlin, it didn't work for me.
我尝试了以下不同的变体:
I tried different variations of the following:
try (writer = OutputStreamWriter(r.getOutputStream())) {
// ...
}
但两者都不起作用.
有谁知道应该用什么代替?显然 Kotlin 语法 没有定义这样的结构,但也许我错过了某物.它定义了 try 块的语法如下:
Does anyone know what should be used instead? Apparently Kotlin grammar doesn't have definition for such a construct, but maybe I'm missing something. It defines grammar for try block as follows:
try : "try" block catchBlock* finallyBlock?;
推荐答案
kotlin stdlib (src).
There is use
-function in kotlin stdlib (src).
使用方法:
OutputStreamWriter(r.getOutputStream()).use {
// by `it` value you can get your OutputStreamWriter
it.write('a')
}
这篇关于在 Kotlin 中尝试资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文