does "object" in kotlin get garbage collected does "object" in kotlin get garbage collected android android

does "object" in kotlin get garbage collected


If we create an object like this:

object Test {    // some functions and properties}

and decompile it to Java, we will see next code:

public final class Test {    public static final Test INSTANCE;   static {      Test var0 = new Test();      INSTANCE = var0;   }}

From the decompiled code, we can see that object creates a Singleton. The initialization happens on a static block. In Java, static blocks are executed on class loading time. The instance of Test class is created at the moment when the classloader loads the class. This approach guarantees lazy-loading and thread-safety. An instance of a singleton object is kept in a static field inside the class of that object. Therefore it isn’t eligible to the garbage collection. The Test is a Singleton, whose lifespan is as long as the lifespan of an app.

Here are some useful information about static variables Android static object lifecycle and static variable null when returning to the app.