Tag: 试用资源

我自己的解决方案,Kotlin的尝试与资源缺席

Kotlin提供了可Closeable对象的use函数,但似乎忘记考虑AutoCloseable (例如,数据库准备语句)的资源尝试与Java完全等效。 我实施了下一个“自制”解决方案: 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) } } 我是Kotlin的新手,我想知道是否在自己的解决方案中丢失了一些重要的东西,这可能会在生产环境中给我带来问题/泄漏。

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

我在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 […]