In Kotlin, you can create a singleton using a companion object:
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?
A companion object is an object that's declared in the same file as a class , and has the same name as the class. A companion object and its class can access each other's private members. A companion object's apply method lets you create new instances of a class without using the new keyword.
companion object is how you define static variables/methods in Kotlin. You are not supposed to create a new instance of Retrofit / ApiService each time you execute a request, however.
In short, companion objects are singleton objects whose properties and functions are tied to a class but not to the instance of that class — basically like the “static” keyword in Java but with a twist.
instance of the class (MyClass) remains in memory for the entire lifecycle of the app?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With