use and Closeable
suggest changeIn Kotlin, there is no special language construct like Java's try (...) (try-with-resources) statement. Instead, Kotlin leverages higher-order inline extension functions to provide safe, deterministic resource cleanup through .use().
Any resource that implements java.io.Closeable or java.lang.AutoCloseable can be safely managed with use. It guarantees that the resource's .close() method is called when the block completes, whether normally or by throwing an exception.
The .use() Function Signature
Defined in kotlin.io:
inline fun <T : Closeable?, R> T.use(block: (T) -> R): R
Since Kotlin 1.8.20, standard library support was also extended to AutoCloseable:
inline fun <T : AutoCloseable?, R> T.use(block: (T) -> R): R
Basic File Reading and Writing
Here is how to safely open, process, and automatically close a file stream:
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
fun copyFile(source: File, destination: File) {
FileInputStream(source).use { input ->
FileOutputStream(destination).use { output ->
input.copyTo(output)
}
}
}
fun readFirstLine(file: File): String? {
return file.bufferedReader().use { reader ->
reader.readLine()
}
}
Even if input.copyTo(output) throws an IOException, both streams are guaranteed to be closed properly.
Idiomatic Line Processing with useLines
For reading files line by line without holding the entire content in memory, Kotlin provides useLines, which wraps a BufferedReader and manages its lifecycle automatically:
import java.io.File
fun countErrors(logFile: File): Int {
return logFile.useLines { lines ->
lines.filter { it.contains("ERROR") }
.count()
}
}
Important: The
Sequence<String>passed touseLinesis only valid within the lambda. If you attempt to return the sequence outside the block, the underlying reader will already be closed, resulting in anIOException: Stream closed. Always materialize the result (e.g.,.toList(),.count(), or.firstOrNull()) inside the lambda.
Managing Database Connections and Transactions
Any JDBC Connection, PreparedStatement, or ResultSet implements AutoCloseable:
import java.sql.DriverManager
fun fetchUserEmail(userId: Long): String? {
val url = "jdbc:postgresql://localhost:5432/mydb"
return DriverManager.getConnection(url, "user", "secret").use { conn ->
val sql = "SELECT email FROM users WHERE id = ?"
conn.prepareStatement(sql).use { stmt ->
stmt.setLong(1, userId)
stmt.executeQuery().use { rs ->
if (rs.next()) rs.getString("email") else null
}
}
}
}
Implementing a Custom Closeable
You can implement Closeable or AutoCloseable on your own components to ensure deterministic cleanup:
import java.io.Closeable
class DatabaseSession(val sessionId: String) : Closeable {
init {
println("Opening session $sessionId")
}
fun executeQuery(sql: String) {
println("Executing '$sql' in session $sessionId")
}
override fun close() {
println("Releasing session $sessionId and rolling back uncommitted changes")
}
}
fun main() {
DatabaseSession("sess_481").use { session ->
session.executeQuery("UPDATE accounts SET balance = balance - 100")
// Automatic cleanup happens at the end of this block
}
}
Exception Handling and Suppression
If an exception occurs within the use block and another exception occurs when closing the resource, Kotlin's use function:
- Catches the secondary close exception.
- Attaches it as a suppressed exception (
Throwable.addSuppressed(...)) to the primary exception. - Re-throws the primary exception.
This guarantees that the original error that triggered the failure is never masked or lost.
import java.io.Closeable
class FaultyResource : Closeable {
override fun close() {
throw IllegalStateException("Error during close()")
}
}
fun main() {
try {
FaultyResource().use {
throw RuntimeException("Primary operation failure")
}
} catch (e: Exception) {
println("Caught primary: ${e.message}") // Primary operation failure
println("Suppressed count: ${e.suppressed.size}") // 1
println("Suppressed: ${e.suppressed[0].message}") // Error during close()
}
}
Best Practices
- Never leak open resources out of
use: Do not return an unconsumedSequence,Iterator, or stream from inside theuseblock. - Prefer Kotlin convenience extensions: Methods like
File.readText(),File.readLines(),File.writeText(), andFile.useLines()already invokeuseinternally. - Combine with extension functions: You can write clean helper extensions for your own types (e.g.,
fun HttpClient.withSession(...)) usinguseunder the hood.