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 -> ... }
}
Create a free account and build your private vault. Share publicly whenever you want.