Memory Leaks in Android | raywenderlich.com

In this Memory Leaks in Android tutorial, you’ll learn how to use the Android Profiler and LeakCanary to detect common leaks and how to avoid them.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/4690472-memory-leaks-in-android

If the anonymous class instance doesn’t call any method, nor read or write any property of the container class, then it wouldn’t retain it.

By my understanding, all inner classes hold implicit reference to its container class object, so how to understand the above statements (if the anonymous class doesn’t access to container object’s method or property, then the inner class doesn’t retain the container class’s reference)

Hi @rainrain ! Thanks for your question.
An anonymous class won’t hold a reference to the container class if you don’t call any method nor access any property of the container class.

Have a look at the following example:

interface MyInterface {
  fun callMe()
}

class MyClass {
  private val myProperty = "This is a test"
  fun method() {
      val myInterface = object : MyInterface {
          override fun callMe() {
              println(myProperty)
          }
      }
      myInterface.callMe()
  }
}

fun main() {
  val myClass = MyClass()
  myClass.method()
}

If you put a breakpoint where you execute myInterface.callMe() you’ll see the following:

Captura de Pantalla 2021-04-12 a la(s) 16.19.05

As you can see, you’re retaining the container class because you’re accessing myProperty.

Now, if you change the code to print a text (instead of the property):

...
override fun callMe() {
  println("This is a test")
}
...

And debug again, you’ll see the following:
Captura de Pantalla 2021-04-12 a la(s) 16.18.07

As you can see it’s not retaining the container class anymore.

1 Like