Effective Kotlin: Item 24 — Favor static member classes over nonstatic

With item 24, Joshua Bloch in Effective Java talks about preferring static member classes over non-static member classes which have a hidden reference to the enclosing instance that can prevent garbage collection (item 7).

On Android, non-static member classes and anonymous classes have been the cause of many memory leaks as, for example, the code below shows an AsyncTask that implicitly holds a reference to the Activity until the long-running task completes:

public class LeakyActivity extends Activity {



private class LongRunningTask extends AsyncTask<Void, Void, String> {

@Override
protected String doInBackground(Void... params) {
// Long running task occurs here

return "Task complete";
}
}
}

Kotlin’s approach to classes means that member classes are static by default with the inner modifier being explicitly added to a class for it to become a non-static member class and thus have an implicit reference to the outer class, i.e. the opposite to Java’s static modifier.

class OuterClass {
// static member class
class NestedClass {}

// non-static member class
inner class InnerClass {}
}

Anonymous classes and lambdas in Kotlin are inner classes, so caution still applies when using those.

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