Good Code
The good version opens the reader and closes it through use in the same expression.
Lesson 08
Close files and streams at the same boundary that opens them.
fun readReviewLines(path: Path): List<String> {
// use closes the reader when parsing succeeds or fails.
return path.toFile().bufferedReader().use { reader ->
reader.readLines()
}
}fun readReviewLines(path: Path): List<String> {
// The reader can stay open when readLines throws.
val reader = path.toFile().bufferedReader()
return reader.readLines()
}The good version opens the reader and closes it through use in the same expression.
The bad version returns before closing the reader. An exception while reading can leak the file descriptor.
use or another explicit close path.