Singleton with parameter in Kotlin

后端 未结 11 1153
无人及你
无人及你 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:24

    Here's a neat alternative from Google's architecture components sample code, which uses the also function:

    class UsersDatabase : RoomDatabase() {
    
        companion object {
    
            @Volatile private var INSTANCE: UsersDatabase? = null
    
            fun getInstance(context: Context): UsersDatabase =
                INSTANCE ?: synchronized(this) {
                    INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
                }
    
            private fun buildDatabase(context: Context) =
                Room.databaseBuilder(context.applicationContext,
                        UsersDatabase::class.java, "Sample.db")
                        .build()
        }
    }
    

提交回复
热议问题