在科特林论点的单例

问题描述:

科林参考资料说,我可以使用 object 创建一个单例>这样的关键字:

The Kotlin reference says that I can create a singleton using the object keyword like so:

object DataProviderManager {
  fun registerDataProvider(provider: DataProvider) {
    //
  }
}

但是,我想将参数传递给该对象.例如,Android项目中的ApplicationContext.

However, I would like to pass an argument to that object. For example an ApplicationContext in an Android project.

有没有办法做到这一点?

Is there a way to do this?

由于对象没有构造函数,因此我执行了以下操作以在初始设置中注入值.您可以随意调用该函数,并且可以随时调用该函数以修改值(或根据需要重建单例).

Since objects do not have constructors what I have done the following to inject the values on an initial setup. You can call the function whatever you want and it can be called at any time to modify the value (or reconstruct the singleton based on your needs).

object Singleton {
    private var myData: String = ""

    fun init(data: String)  {
        myData = data
    }

    fun singletonDemo() {
        System.out.println("Singleton Data: ${myData}")
    }
}