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