Effective Kotlin: Item 8 — Avoid finalizers and cleaners
With Joshua Bloch’s recently updated book, Effective Java, he talks about avoiding the use of finalizers and, if running Java 9, their replacement cleaners. One suggestion is to use try-with-resources
, which doesn’t exist in Kotlin.
Instead, Kotlin introduces the extension function use
which will call close()
on a Closeable
when the block provided completes or throws an exception.
inputStream.use {
// do something with the stream
it.read()
}
If using a class that doesn’t extend Closeable
, take a look at the implementation of use as it is easy enough to make an extension method to replicate this functionality.
Each week I am looking at “items” from Joshua Bloch’s well-respected book, Effective Java to see how it applies to Kotlin. You can find the rest of the items I’ve covered at Effective Kotlin. Please let me know your thoughts.