在Kotlin尝试资源 [英] Try-with-resources in Kotlin
本文介绍了在Kotlin尝试资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试在Kotlin中编写等效的try-with-resources代码时,它对我不起作用。
When I tried to write an equivalent of 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 may be I'm missing something. It defines grammar for try block as follows:
try : "try" block catchBlock* finallyBlock?;
推荐答案
使用
-function in 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屋!
查看全文