kotlin - 在 Kotlin 中试用资源

当我试图写一个等效的 Java try-with-resources Kotlin 中的声明,它对我不起作用。

我尝试了以下不同的变体:

try (writer = OutputStreamWriter(r.getOutputStream())) {
    // ...
}

但两者都不起作用。有谁知道应该改用什么?

显然 Kotlin 语法 doesn't include这样的构造,但也许我错过了一些东西。它为 try block 定义语法如下:

try : "try" block catchBlock* finallyBlock?;

最佳答案

有一个use kotlin-stdlib ( src ) 中的函数。

使用方法:

OutputStreamWriter(r.getOutputStream()).use {
    // `it` is your OutputStreamWriter
    it.write('a')
}

https://stackoverflow.com/questions/26969800/

相关文章:

asynchronous - Kotlin协程中的launch/join和async/await有什

kotlin - 什么是 Kotlin 双键 (!!) 运算符?

kotlin - bool 值的使用?在 if 表达式中

kotlin - Kotlin 中的单个感叹号

random - 如何在 Kotlin 中获取随机数?

android-studio - Android Studio 3.0 - 找不到方法 'com.a

hibernate - 带有 JPA : default constructor hell 的 Ko

android-studio - Unresolved reference : kotlinx

design-patterns - 如何在 Kotlin 中实现 Builder 模式?

java - Java 的 String[] 的 Kotlin 等价物是什么?