Kotlin

use { } — Auto-Close Resources

admin by @admin ADMIN
11m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`use { }` calls `close()` on any `Closeable` (file, stream, JDBC connection, …) when the block exits — even on exception. Kotlin's try-with-resources.
Kotlin
Raw
import java.io.File

fun main() {
    // Whatever happens inside the block, the reader closes cleanly
    File("/etc/hosts").bufferedReader().use { reader ->
        reader.forEachLine { line ->
            if (line.isNotBlank()) println(line)
        }
    }

    // Nesting — both close even if the inner one throws
    File("in.txt").bufferedReader().use { r ->
        File("out.txt").bufferedWriter().use { w ->
            r.forEachLine { line -> w.write(line.uppercase()); w.newLine() }
        }
    }

    // Works with any AutoCloseable — JDBC connections, channels, sockets
    // java.sql.DriverManager.getConnection(url).use { conn -> ... }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.