试用资源:Kotlin 中的“使用”扩展函数并不总是有效

2022-09-03 09:34:51

我在 Kotlin 中表达 Java 的 try-with-resources 构造时遇到了一些麻烦。在我的理解中,每个作为实例的表达式都应该提供扩展函数。AutoClosableuse

下面是一个完整的示例:

import java.io.BufferedReader;
import java.io.FileReader;

import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;

public class Test {

    static String foo(String path) throws Throwable {
        try (BufferedReader r =
           new BufferedReader(new FileReader(path))) {
          return "";
        }
    }

    static String bar(TupleQuery query) throws Throwable {
        try (TupleQueryResult r = query.evaluate()) {
          return "";
        }
    }
}

Java-to-Kotlin 转换器创建以下输出:

import java.io.BufferedReader
import java.io.FileReader

import org.openrdf.query.TupleQuery
import org.openrdf.query.TupleQueryResult

object Test {

    @Throws(Throwable::class)
    internal fun foo(path: String): String {
        BufferedReader(FileReader(path)).use { r -> return "" }
    }

    @Throws(Throwable::class)
    internal fun bar(query: TupleQuery): String {
        query.evaluate().use { r -> return "" } // ERROR
    }
}

foo工作正常,但 中的代码无法编译:bar

Error:(16, 26) Kotlin: Unresolved reference.
None of the following candidates is applicable
because of receiver type mismatch: 
public inline fun <T : java.io.Closeable, R>
???.use(block: (???) -> ???): ??? defined in kotlin.io

query.evaluate()来自芝麻和实现。这是一个Kotlin错误,还是有原因它不起作用?AutoClosable


我正在使用 IDEA 15.0.3 和 Kotlin 1.0.0-beta-4584-IJ143-12 和以下版本:sasame-runtime

<groupId>org.openrdf.sesame</groupId>
<artifactId>sesame-runtime</artifactId>
<version>4.0.2</version>

答案 1

Kotlin 目前面向 Java 6,因此其标准库不使用该接口。该函数仅支持 Java 6 接口。请参阅问题跟踪器以供参考。AutoCloseableuseCloseable

您可以在项目中创建函数的副本,并将其修改为替换为:useCloseableAutoCloseable

public inline fun <T : AutoCloseable, R> T.use(block: (T) -> R): R {
    var closed = false
    try {
        return block(this)
    } catch (e: Exception) {
        closed = true
        try {
            close()
        } catch (closeException: Exception) {
            e.addSuppressed(closeException)
        }
        throw e
    } finally {
        if (!closed) {
            close()
        }
    }
}

答案 2

Kotlin 1.1+ 有一个标准库,它面向 Java 8 以支持模式 - kotlin-stdlib-jre8Closeable resource

格雷德尔

compile "org.jetbrains.kotlin:kotlin-stdlib:1.1.1"
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:1.1.1"

马文

<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib-jre8</artifactId>
    <version>1.1.1</version>
</dependency>

样本

val resource: AutoCloseable = getCloseableResource() 
resource.use { r -> //play with r }

推荐