Hi there , what is difference between object and c...
# android
m
Hi there , what is difference between object and companion object in singleton pattern ? and what's good way ? , Do both methods have no problem when using? !!!
z
This Kotlinlang page describes the companion object's benefits over regular objects https://kotlinlang.org/docs/object-declarations.html#companion-objects
Mostly that you can reference it by just the classname, e.g.
Counter
will point to it
In your code examples though, you could just omit the nested
object
entirely, and make
Counter
itself an object, if you want it to be a singleton instance
p
There is a subtle difference between the declarations in terms of object creation time -
Copy code
object MySingleton {
}
and
Copy code
class SomeClass {
    companion object {
    }
}
The
companion object
will get created when the first instance of
SomeClass
is created. In the case of the Kotlin singleton object, it will be created when it is first used.