try-with-resources: “use” extension function in Kotlin does not always work

后端 未结 4 1449
抹茶落季
抹茶落季 2021-01-11 10:51

I had some trouble expressing the Java\'s try-with-resources construct in Kotlin. In my understanding, every expression that is an instance of AutoClosable shou

4条回答
  •  北海茫月
    2021-01-11 11:16

    Kotlin 1.1+ has a standard library that targets Java 8 to support Closeable resource pattern - kotlin-stdlib-jre8

    Gradle

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

    Maven

    
        org.jetbrains.kotlin
        kotlin-stdlib
        1.1.1
    
    
        org.jetbrains.kotlin
        kotlin-stdlib-jre8
        1.1.1
    
    

    Sample

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

提交回复
热议问题