Try-with-resources
Java7 added the notion of AutoCloseable
and the try-with-resources statement.
This statement allows us to provide a set of resources that would be automatically closed after the code is done with them. No more risk (or at least less risk) of forgetting to close a file.
Before Java7, that was a total mess:
BufferedReader br = null; // Nulls are bad, we know that
try {
br = new BufferedReader(new FileReader("/some/peth"));
System.out.println(br.readLine());
}
finally {
if (br != null) { // Explicit check
br.close(); // Boilerplate
}
}
After Java7:
try (BufferedReader br = new BufferedReader(new FileReader("/some/peth"))) { System.out.println(br.readLine()); }
In Kotlin, the this
statement is replaced with the use()
function:
val br = BufferedReader(FileReader(""))
br.use {
println(it.readLine())
}