Singleton with parameter in Kotlin

后端 未结 11 1135
无人及你
无人及你 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条回答
  •  萌比男神i
    2020-11-30 22:16

    I am not entirely sure why would you need such code, but here is my best shot at it:

    class TasksLocalDataSource private constructor(context: Context) : TasksDataSource {
        private val mDbHelper = TasksDbHelper(context)
    
        companion object {
            private var instance : TasksLocalDataSource? = null
    
            fun  getInstance(context: Context): TasksLocalDataSource {
                if (instance == null)  // NOT thread safe!
                    instance = TasksLocalDataSource(context)
    
                return instance!!
            }
        }
    }
    

    This is similar to what you wrote, and has the same API.

    A few notes:

    • Do not use lateinit here. It has a different purpose, and a nullable variable is ideal here.

    • What does checkNotNull(context) do? context is never null here, this is guarantied by Kotlin. All checks and asserts are already implemented by the compiler.

    UPDATE:

    If all you need is a lazily initialised instance of class TasksLocalDataSource, then just use a bunch of lazy properties (inside an object or on the package level):

    val context = ....
    
    val dataSource by lazy {
        TasksLocalDataSource(context)
    }
    

提交回复
热议问题