在 Kotlin 中使用参数的单例 [英] Singleton with argument in Kotlin

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

问题描述

Kotlin 参考说我可以使用 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}")
    }
}

这篇关于在 Kotlin 中使用参数的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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