Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton with argument in Kotlin [duplicate]

Tags:

kotlin

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?

like image 764
jakk Avatar asked Oct 14 '15 14:10

jakk


People also ask

How would you create a singleton with parameter in Kotlin?

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.

Is Kotlin lazy singleton?

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.

How can you achieve Singleton Pattern in Kotlin?

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.

Is companion object singleton Kotlin?

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).


2 Answers

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}")     } } 
like image 177
Jeremy Lyman Avatar answered Sep 23 '22 00:09

Jeremy Lyman


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) 
like image 28
breandan Avatar answered Sep 22 '22 00:09

breandan