public class Singleton {
private static Singleton instance = null;
private Singleton(){
}
public synchronized static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
doSomeInitializationIfRequired();
return instance;
}
}
here getInstance() method is called whenever we request for the Instance where we can add code if we want to do something when the instance is called from any where everytime.
is there some way to override instance variable get() like this with Kotlin Objects
e.g.
object SomeSingleton {
get() = {
doSomeInitializationIfRequired()
}
}
I know i can write
init {
}
but that will be called only once.
I wouldn't use object
for this type of singleton. You can do it more like the Java way.
class Singleton private constructor() {
companion object {
private var _instance = Singleton()
val instance: Singleton
get() = synchronized(this) {
doSomeInitializationIfRequired()
_instance
}
}
}
If you need parameters for the constructor or for doSomeInitializationIfRequired()
, you can replace val instance
with a getInstance
function. This is common on Android where your singleton might need a reference to the Application instance.
class Singleton private constructor(val application: Application) {
companion object {
private val instance: Singleton? = null
fun getInstance(application: Application): Singleton = synchronized(this) {
val value = instance ?: Singleton(application).also { instance = it }
doSomeInitializationIfRequired(application)
value
}
}
}