Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destroy an singleton Object in Kotlin and force to call init block

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?

like image 718
Bhuvanesh BS Avatar asked Feb 23 '18 10:02

Bhuvanesh BS


2 Answers

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.

like image 178
yole Avatar answered Sep 16 '22 21:09

yole


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.

like image 26
Suraj Nair Avatar answered Sep 17 '22 21:09

Suraj Nair