Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试使用Kotlin中的资源_Kotlin_Extension Methods_Try With Resources - Fatal编程技术网

尝试使用Kotlin中的资源

尝试使用Kotlin中的资源,kotlin,extension-methods,try-with-resources,Kotlin,Extension Methods,Try With Resources,当我试图用Kotlin中的参考资料代码编写一个Javatry-的等价物时,它对我不起作用 我尝试了以下不同的变体: try (writer = OutputStreamWriter(r.getOutputStream())) { // ... } 但两者都不起作用 有人知道应该用什么来代替吗? 显然,Kotlin语法适用于这样的构造,但也许我遗漏了一些东西。它对try块的语法定义如下: try : "try" block catchBlock* finallyBlock?; kotl

当我试图用Kotlin中的参考资料代码编写一个Java
try
-的等价物时,它对我不起作用

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

try (writer = OutputStreamWriter(r.getOutputStream())) {
    // ...
}
但两者都不起作用

有人知道应该用什么来代替吗? 显然,Kotlin语法适用于这样的构造,但也许我遗漏了一些东西。它对try块的语法定义如下:

try : "try" block catchBlock* finallyBlock?;

kotlin stdlib()中有
use
-函数

如何使用它:

OutputStreamWriter(r.getOutputStream()).use {
    // by `it` value you can get your OutputStreamWriter
    it.write('a')
}
fun main() {
    val s = MyServer()
    s.use {
        println("begin")
    }
    println("end")
}

编辑:以下响应对于Kotlin 1.0.x仍然有效。对于Kotlin1.1,支持一个针对Java8的标准库,以支持可关闭的资源模式

对于不支持“use”函数的其他类,我使用参考资料进行了以下自制尝试:

package info.macias.kotlin

inline fun <T:AutoCloseable,R> trywr(closeable: T, block: (T) -> R): R {
    try {
        return block(closeable);
    } finally {
        closeable.close()
    }
}
TL;DR:没有特殊语法,只是一个函数 与Java相反,Kotlin对此没有特殊的语法。相反,请尝试使用资源,它是作为标准库函数
use
提供的

FileInputStream("filename").use { fis -> //or implicit `it`
   //use stream here
} 

使用
实现
花括号中的部分是
use
中的
(此处将lambda作为参数传递)。阻塞完成后,您可以确保
FileInputStream
已关闭。

因为此StackOverflow帖子位于当前“kotlin closeable example”搜索结果的顶部附近,但其他答案(或官方文档)均未清楚解释如何扩展
closeable
(又称java.io.Closeable),我想我应该添加一个示例,说明如何创建自己的类来扩展
Closeable

import java.io.Closeable

class MyServer : Closeable {
    override fun close() {
        println("hello world")
    }
}
然后使用它:

OutputStreamWriter(r.getOutputStream()).use {
    // by `it` value you can get your OutputStreamWriter
    it.write('a')
}
fun main() {
    val s = MyServer()
    s.use {
        println("begin")
    }
    println("end")
}

在Kotlin游乐场上可以看到这个例子。

我强烈建议在课堂上使用AutoCloseable

自动关闭对象在退出时自动调用 使用已在中声明对象的资源块重试 资源规范头

例如:

class Resource : AutoCloseable {
    fun op1() = println("op1")
    override fun close() = println("close up.")
}
在主要功能方面:

Resource().use {
    it.op1()
}
输出:

> op1
close up.

我非常喜欢扩展方法。你可以做很多事情,不需要额外的语言功能。除此之外,实际上还有一个扩展属性来获得
OutputStreamWriter
r.outputStream.writer.use{…}
链接到参考文档,该文档演示了
use
扩展:如何更好地使用multi“use”?
FileOutputStream(into)。使用{val mergingStream=BufferedOutputStream(it)。使用{}
刷新怎么样?我应该在使用结束块刷新OutputStream吗?这不能正确处理从finally子句引发的异常,这是Java中添加try with resources的原因之一。这只是一个简单的
try/finally
> op1
close up.