尝试使用资源:Kotlin中的“使用”扩展功能并不总是有效

时间:2016-02-01 17:31:14

标签: java kotlin try-with-resources

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

这是一个完整的例子:

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()来自Sesame并实施AutoClosable。这是一个Kotlin bug,还是有原因导致它不起作用?

我正在使用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>

4 个答案:

答案 0 :(得分:19)

Kotlin目前面向Java 6,因此其标准库不使用AutoCloseable接口。 use函数仅支持Java 6 Closeable接口。请参阅the issue tracker以供参考。

您可以在项目中创建use功能的副本,并修改它以将Closeable替换为AutoCloseable

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()
        }
    }
}

答案 1 :(得分:5)

Kotlin 1.1+有一个标准库,以Java 8为目标,支持Closeable resource模式 - kotlin-stdlib-jre8

<强>摇篮

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

<强>的Maven

<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 }

答案 2 :(得分:1)

对于不支持“使用”功能的课程,我已经完成了下一个自制的资源尝试:

inline fun <T:AutoCloseable,R> trywr(closeable: T, block: (T) -> R): R {
    try {
        return block(closeable);
    } finally {
        closeable.close()
    }
}

然后您可以通过下一种方式使用它:

fun countEvents(sc: EventSearchCriteria?): Long {
    return trywr(connection.prepareStatement("SELECT COUNT(*) FROM event")) {
        var rs = it.executeQuery()
        rs.next()
        rs.getLong(1)
    }
}

答案 3 :(得分:1)

只需确保classpath中的kotlin-stdlib-jdk7.jar,默认情况下未添加