hi guys!when you want to create a Singleton ,which...
# android
d
hi guys!when you want to create a Singleton ,which one would you choose? ‘object’ or ‘companion object’? what is different?
a
If the object is closely related with another class, you can make it a companion. If it's independent, you can make it its own object
It's similar to how you would choose to make a public static utility class or a static class inside another class. It's more or less just naming
d
thank you for your answer!i wrote a double-checked Singleton with ‘object’ and ‘companion object’ , and decompiler them to java, object use static block to init , companion object use inner class and static variable to init , one more question: whats difference between static block and static variable?
a
This is more of a java question and you’d have to look up the order for which static blocks are called. See https://stackoverflow.com/questions/40700373/the-execute-order-of-the-static-methodjava
d
kotlin doc explain it object and companion object: object declarations are initialized lazily, when accessed for the first time; a companion object is initialized when the corresponding class is loaded (resolved), matching the semantics of a Java static initializer. http://kotlinlang.org/docs/reference/object-declarations.html
But i think both of them init when the class is loaded ?
sorry! I misunderstood the explain! i got it!