CoDe
CoDe

Reputation: 11146

Kotlin Memory allocation behaviour for object class and companion object

Kotlin provide a better way to create singleton object and companion object to access class member via class name. Cool this is !!

But how the memory allocation work for both declaration, does this same work like static in java and remain retain till application lifecycle.

I have gone through couple of resource like this and this, but it did not helped me much. Any guideline !!

Upvotes: 1

Views: 1330

Answers (1)

anber
anber

Reputation: 3665

I believe the easiest way to answer you question is to make simple project in Kotlin, than got to Tools - Kotlin - Show Kotlin bytecode in IntelliJ Idea and than Decompile on the opened page - and you will see on what exactly Kotlin code translated. For example you have Kotlin code:

fun main(args: Array<String>) {
    Test.test()
}

class Test {

    companion object TestCompanion{
        fun test() {
            println("TestCompanion")
        }
    }

}

Decompiled result:

public final class MainKt {
   public static final void main(@NotNull String[] args) {
      Test.TestCompanion.test();
   }
}

public final class Test {
   public static final Test.TestCompanion TestCompanion = new Test.TestCompanion();

   public static final class TestCompanion {
      public final void test() {
         System.out.println("TestCompanion");
      }
   }
}

Upvotes: 4

Related Questions