hi guys!when you want to create a Singleton ,which one would you choose? ‘object’ or ‘companion object’? what is different?
a
Allan Wang
01/12/2019, 12:36 AM
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
Allan Wang
01/12/2019, 12:36 AM
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
dididi
01/12/2019, 12:48 AM
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?
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
dididi
01/12/2019, 1:01 AM
But i think both of them init when the class is loaded ?