Singleton with argument in Kotlin

前端 未结 5 1002
醉酒成梦
醉酒成梦 2020-12-05 23:35

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

object DataProviderManager {
  fun registerDataProvider(pr         


        
5条回答
  •  情深已故
    2020-12-06 00:01

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

提交回复
热议问题