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?
In Kotlin, we need to use the object keyword to use Singleton class. The object class can have functions, properties, and the init method. The constructor method is not allowed in an object so we can use the init method if some initialization is required and the object can be defined inside a class.
Kotlin intentionally avoids the confusion people have with singletons in Java. And avoids the "wrong versions" of this pattern -- of which there are many. It instead provides the simpler and the safest form of singletons. Given the use of lazy() , if you have other members each would individually be lazy.
If we especially conversation around Android, we know that in Android we by and large have to pass a context instance to init block of a singleton. We can do it by using Early initialization and Apathetic initialization. In early initialization, all the components are initialized within the Application.
The companion object is an object (singleton) that companies (belongs to) a class. (this is an other way for implementing static methods in other languages).
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 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With