Part 08 / Topic 4 of 7
use {}: closing resources safely
A BufferedReader/BufferedWriter holds an open OS file handle until it's closed -- leaving it
open is a real resource leak. use {} runs the block and guarantees close() afterward, whether
the block finishes normally or throws, the same job a try/finally would do by hand, written
once in the standard library instead of at every call site.
val log = File("events.txt")
// File.bufferedWriter() opens a BufferedWriter; use {} guarantees close() runs when the
// block ends, whether it finishes normally or throws
log.bufferedWriter().use { writer ->
writer.write("Order placed")
writer.newLine()
writer.write("Payment received")
writer.newLine()
}
println("After writing, file exists: ${log.exists()}")
log.bufferedReader().use { reader ->
var line = reader.readLine()
while (line != null) {
println("Read: $line")
line = reader.readLine()
}
}
After writing, file exists: true
Read: Order placed
Read: Payment received
This was checked for real, not assumed: a second bufferedWriter() call that writes one line
and then deliberately throws still leaves that one line safely on disk, because use {} closes
(and flushes) the writer on the way out, before the exception keeps propagating.
try {
log.bufferedWriter().use { writer ->
writer.write("Shipped")
writer.newLine()
throw RuntimeException("simulated failure after writing one more line")
}
} catch (e: RuntimeException) {
println("Caught: ${e.message}")
}
// the writer's use {} block already closed and flushed "Shipped" before the exception
// propagated out -- the file is readable right away, not locked by a half-open writer
println("File content after the exception:")
log.bufferedReader().use { reader ->
reader.forEachLine { println(" $it") }
}
Caught: simulated failure after writing one more line
File content after the exception:
Shipped
Notice the file now contains only "Shipped", not the earlier two lines -- bufferedWriter()
opens in overwrite mode by default, same as writeText(), so this second use {} block replaced
the file's content the moment it opened, before anything else happened. The point this proves is
narrower but just as real: whatever was written inside the block before the exception made it
to disk, because use {} closed the writer on the way out.
🔍 Going deeper:
use {}works on anything implementingCloseable(the JDK interface bothBufferedReaderandBufferedWriterimplement), not just files -- the same pattern closes a database connection or a network socket. Stage 2's Part 11 (build tooling) and thekotlin-engineer-coursereference material both lean onuse {}for exactly this reason.
Full program: examples/04_use_blocks.kt.
Done here? The practice set for Part 8 — including the solutions — is on the part page.