[SOLVED] Try with resources with `AutoClosable`


#1

I’m using TensorFlow which provides

public final class Graph implements AutoCloseable

However I am getting an error when I try to use the try-with-resources construct of Kotlin like this…

Graph().use {
    ....
}

When I look into it, it appears that use requires a Closeable and does not work with an AutoClosable and AutoClosable does not inherit from Closable and is only available in JDK7 and up.

Is there another way around this?

I just noticed this from Kotlin needs try-with-resources

Here are the problems with the Closeable.use extension method:

  • Doesn’t work with Autocloseable (easy to fix, but seriously? this is a can of worms, but Kotlin’s stdlib needs to be 100% compatible with whatever the latest JDK is. In fact, you probably need to version the stdlib (and, perhaps, Kotlin itself) together with the JDK.)

#2

You need to add kotlin-stdlib-jre7 or kotlin-stdlib-jre8 as a dependency to your project; it defines a version of use that works with AutoCloseable.


#3

Thanks that worked!


#4

I’m running into this same problem in kotlin 1.2 using kotlin-stdlib-jdk8. If I change back to 1.1.50 and kotlin-stdlib-jre8 it compiles fine.