Singleton with argument in Kotlin

2019-01-14 21:11发布

问题:

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

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

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?

回答1:

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}")
    }
}


回答2:

Kotlin has a feature called Operator overloading, letting you pass arguments directly to an object.

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

  operator fun invoke(context: ApplicationContext): DataProviderManager {
      //...
      return this
  }
}

//...
val myManager: DataProviderManager = DataProviderManager(someContext)


回答3:

There are also two native Kotlin injection libraries that are quite easy to use, and have other forms of singletons including per thread, key based, etc. Not sure if is in context of your question, but here are links to both:

  • Injekt (mine, I'm the author): https://github.com/kohesive/injekt
  • Kodein (similar to Injekt): https://github.com/SalomonBrys/Kodein

Typically in Android people are using a library like this, or Dagger, et al to accomplish parameterizing singletons, scoping them, etc.



回答4:

I recommend that you use this form to pass arguments in a siglot in kotlin debit that the object your constructor is deprived and blocked:

object Singleton {

fun instance(context: Context): Singleton {
    return this
}

fun SaveData() {}

}

and you call it this way in the activity

Singleton.instance(this).SaveData()


标签: kotlin