Singleton with parameter in Kotlin

后端 未结 11 1127
无人及你
无人及你 2020-11-30 21:51

I am trying to convert an Android app from Java to Kotlin. There are a few singletons in the app. I used a companion object for the singletons without constructor parameters

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 22:35

    Singletons
    

    Singletons are used often enough for a simpler way of creating them to exist. Instead of the usual static instance, getInstance() method and a private constructor, Kotlin uses the object notation. For consistency, object notation is also used to define static methods.

     object CommonApiConfig {
    private var commonApiConfig: CommonApiConfig? = null
    fun getInstance(): CommonApiConfig {
        if (null == commonApiConfig) {
            commonApiConfig = CommonApiConfig
           }
        return CommonApiConfig.commonApiConfig!!
       }
    }
    

提交回复
热议问题