Is "object" really a singleton?

Hi guys,

Question about “object”. It is explained that it is a singleton, so can you explain that to me ?
I just created the simplest object I can :

object MySingleton {
    var myVar: Int = 1
}

As it is a singleton I expect myVar will be an instance variable. Translated to Java it should be something like this :

class MySingleton {
    public int myVar = 1;
    public static MySingleton INSTANCE;
}

Here, myVar is only accessible by INSTANCE.

But, when I try to decompile my kotlin singleton, I get this thing :

public final class MySingleton {
   private static int myVar;
   public static final MySingleton INSTANCE;

   public final int getMyVar() {
      return myVar;
   }

   public final void setMyVar(int var1) {
      myVar = var1;
   }

   private MySingleton() {
   }

   static {
      MySingleton var0 = new MySingleton();
      INSTANCE = var0;
      myVar = 1;
   }
}

myVar is not an instance variable ! It is just a static one ! Ok, the behavior is the same but under the hood isn’t. Variables won’t be a “real” part of singleton. Why variables are static ?

Thank you guys :ok_hand:

I think the reason is that it’s easier for the JVM to do optimizations that way, but as you said it doesn’t change the behavior. In general static dispatch is more performant than dynamic and there might be a few other optimizations possible this way.

Also note that kotlin does not have the concept of fields. So the statement that the fields won’t be a real part of the singleton doesn’t make any sense in kotlin. Kotlin will always try to use the best method of providing fields under the hood and in that case this means singletons (or at least that is what the kotlin team decided to use here).