I just to wish clarify some methodology using singletons in Kotlin.
I have this class:
class TestClass {
companion object {
val instance = TestClass()
fun runSync2() {
Log.d("TAG", "Running sync2")
}
init {
Log.d("TAG", "Init companion")
}
}
init {
Log.d("TAG", "Init class")
}
fun runSync1() {
Log.d("TAG", "Running sync1")
}
}
And this test functions:
1. TestClass.instance.runSync1()
2. TestClass.runSync2()
3. TestClass().runSync1()
- When calling function 1 twice, init inside companion object will be called once. So only one instance of TestClass is created and run runSync1() twice, correct?
- When calling function 2 twice, init inside companion object will be called once. So only one instance of TestClass is created and run runSync2() twice, correct? So what is the difference between 1 and 2?
- When calling function 2 twice, 2 instances of TestClass crated, 2 init inside class will run and 2 runSync1 will run independently?
Can you please provide more clarification and correct the wrong parts?