Effective Kotlin: Item 7 — Eliminate obsolete object references

On Android, accidentally holding onto a reference such as to the Activity leads to out of memory crashes that can be hard to find showing the importance of item 7 of Joshua Bloch’s excellent book Effective Java.

One of the easiest ways to leak an activity on Android is with inner classes, especially the Handler class. How to Leak a Context talks about this in a lot more detail as does AlertDialog causes a memory leak.

A less visible place memory leaks can occur is when using Butterknife in fragments as you must call unbind. I wrote a small library to help detect scenarios like this when someone hasn’t called an unbind function so if you write APIs check out leaktracker.

Google also provides some tips on Avoiding memory leaks on their blog, and tools such as Leakcanary from Square are invaluable in spotting memory leaks too.

On reading these articles, one tip you’ll hopefully see in common is to avoid inner classes. A nicety of Kotlin is by default nested classes are implicitly static, whereas in Java they are not, significantly reducing the chances of some of these issues. To allow a nested class to reference its outer class, you explicitly add the inner keyword. What you still have to be aware of though is that anonymous classes, and thus also lambdas, will hold a reference to their containing class.

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.

Matt Dolan has been eating doughnuts and developing with Android since the dark days of v1.6.

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