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

后端 未结 4 1473
抹茶落季
抹茶落季 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:37

    For classes that do not support the "use" function, I have done the next homemade try-with-resources:

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

    Then you can use it the next way:

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

提交回复
热议问题