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.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store