Closing DB connection

What is idiomatic method for closing a jdbc connection in Kotlin? Here is what I have been using:

val conn = DB.getConnection()
try {
    foo(conn)
} finally {
    conn.close()
}

I get a suggestion to convert “try-finally” to “use” which gives me this code:

conn.use { conn ->
    foo(conn)
}

which doesn’t compile because there is no use method on Connection.

It should be possible to apply the use function to any object which implements the AutoCloseable interface.

java.sql.Connection is a sub-interface of AutoCloseable and so I’m surprised that it doesn’t compile.

But, if it doesn’t, then your try/finally close() approach is fine as use is basically a wrapper for that when using AutoCloseables and similar to Java’s try-with-resources statement.

AutoCloseable was introduced in JDK 7. You should add dependency on, at least, kotlin-stdlib-jre7 (you can also have kotlin-stdlib-jre8 instead) to your project to be able to use use with AutoCloseable classes like JDBC Connection.

1 Like

Alternatively you can implement use for database Connections yourself if you really can’t use jdk 7 (why?? jdbc does not exist on Android anyway).