在Kotlin中,可以使用伴生对象创建单例:

class MyClass {
   companion object {
        fun doSomething() {

        }
    }
}

According to the Kotlin docs, it states:

Note that, even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects...

https://kotlinlang.org/docs/reference/object-declarations.html

Does this mean that after using a function in the companion object, the instance of the class (MyClass) remains in memory for the entire lifecycle of the app? Is there a way in Android Studio to check to see if this is the case?

推荐答案

instance of the class (MyClass) remains in memory for the entire lifecycle of the app?

JVM中的伴生对象

in kotlin

class MyClass {
   companion object {
        fun doSomething() {

        }
    }
}

MyClass(Kotlin) converted in JVM

public final class MyClass {
   public static final MyClass.Companion Companion = new MyClass.Companion(null);

   public static final class Companion {
      public final void doSomething() {
      }

      private Companion() {
      }

      public Companion() {
         this();
      }
   }
}

As above code, companion object is declared as Companion class in JVM, and it's created as static field inside MyClass class. Thus, isn't collected by gc. So, the memory of object(Companion) is remained during the ProcessLifecycle. static final object isn't released in normal case.

In conclusion, if referred to MyClass.Companion instance in application, that instance will not be garbage collected. (on general Classloaders).

*If not referred to MyClass.Companion instance in application, it may be removed by code shrinking feature.

Is there a way in Android Studio to check to see if this is the case?

You can see through android studio > profiler > Heap dump.

Reference

Kotlin相关问答推荐

如何在Kotlin中为两个数据类创建可重用的方法?

带有Spring Boot和Kotline的可嵌入实体

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

如何进行基于lambda/谓词的两个列表的交集?

为什么这两个 Kotlin 协程函数不一样?

是什么让 Kotlin 中的 String 类能够使用方括号?

如何在 kotlin 中通过反射设置委托属性值?

Kotlin 中列表或数组的乘积

为什么 IntelliJ Idea 无法识别我的 Spek 测试?

比较 Kotlin 中的可比对象列表

`DataBindingUtil` 中的 `bind`、`inflate` 和 `setContentView` 有什么区别

无法在 kotlin android 中以编程方式禁用 EditText

Kotlin - mutableMapOf() 会保留我输入的顺序

Kotlin中的测试无法访问受保护(protected)的方法

未找到导入 kotlinx.coroutines.flow.*

编译错误:-Xcoroutines has no effect: coroutines are enabled anyway in 1.3 and beyond

Jetpack Compose-居中文本

判断EditText是否为空kotlin android

使用 Moshi/Retrofit2 访问深度嵌套的 JSON 数组

具有多个 parameter的 Kotlin 枚举