In Java, we can destroy the Singleton Object by below method.
public class MySingleton {
private static MySingleton ourInstance = null;
private MySingleton() {
}
public static MySingleton getInstance() {
if(ourInstance == null)
ourInstance = new MySingleton();
return ourInstance;
}
private void destroy(){
ourInstance = null;
}
}
so the constructor will be called the next time.
In the same way how to destroy the Kotlin Singleton object.
object CacheManager{
init {
//some operations
}
fun destroy(){
//How to destroy?
}
}
I need to destroy the Object and make the init block called again. How can I achieve this?
This is not possible in Kotlin; objects do not have the concept of being destroyed. If you need this possibility, you should not use an object
, but instead use a regular class
and implement the destroy logic manually, similarly to how you do this in Java.
I just converted your JAVA code to Kotlin using android studio and the result is looks like a singleton class which allows to destroy singleton object.
class MySingleton private constructor() {
fun destroy() {
ourInstance = null
}
companion object {
private var ourInstance: MySingleton? = null
val instance: MySingleton
get() {
if (ourInstance == null)
ourInstance = MySingleton()
return ourInstance!!
}
}
var b: String="Default value"
}
You can test this by following code
var singleton:MySingleton= MySingleton.instance
singleton.b="Singleton Object Initlized"
Log.d("Value",singleton.b)
singleton.destroy()
singleton= MySingleton.instance
Log.d("Reset",singleton.b)
May be this approach is wrong. If this is wrong then i will delete the answer, please let me know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With