在科特林论点的单例 [英] Singleton with argument in Kotlin

查看:77
本文介绍了在科特林论点的单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

科林参考资料说,我可以使用 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}")
    }
}

这篇关于在科特林论点的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆