Kotlin

Lesson 08

Resource use boundaries

Close files and streams at the same boundary that opens them.

Good Code

src/main/kotlin/reviews/ReviewImport.kt
fun readReviewLines(path: Path): List<String> {
    // use closes the reader when parsing succeeds or fails.
    return path.toFile().bufferedReader().use { reader ->
        reader.readLines()
    }
}

Bad Code

ReviewImport.kt
fun readReviewLines(path: Path): List<String> {
    // The reader can stay open when readLines throws.
    val reader = path.toFile().bufferedReader()
    return reader.readLines()
}

Review Notes

What to review

Good Code

The good version opens the reader and closes it through use in the same expression.

Bad Code

The bad version returns before closing the reader. An exception while reading can leak the file descriptor.

Takeaways

  • Kotlin resource review should pair every opened stream with use or another explicit close path.