Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make this singleton simpler in Kotlin?

How can I make this singleton simpler in Kotlin for the Android room database initialization?

@Database(entities = arrayOf(Book::class, User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {

    abstract fun bookModel() : BookDao
    abstract fun userModel() : UserDao

    companion object {
        private var INSTANCE: AppDatabase? = null

        fun getInMemoryDatabase(context: Context): AppDatabase {
            if (INSTANCE == null) {
                INSTANCE = Room.inMemoryDatabaseBuilder(context.applicationContext, AppDatabase::class.java).build()
            }
            return INSTANCE!!
        }

        fun destroyInstance() {
            INSTANCE = null
        }
    }
}
like image 288
s-hunter Avatar asked Nov 23 '25 21:11

s-hunter


1 Answers

You can use an array literal ([]) instead of arrayOf and you can use the elvis operator for the null check. See here.

@Database(entities = [Book::class, User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {

    abstract fun bookModel() : BookDao
    abstract fun userModel() : UserDao

    companion object {
        private var INSTANCE: AppDatabase? = null

        fun getInMemoryDatabase(context: Context): AppDatabase { 
            INSTANCE = INSTANCE ?: Room.inMemoryDatabaseBuilder(context.applicationContext, AppDatabase::class.java).build()
            return INSTANCE!!
        }
    
        fun destroyInstance() {
            INSTANCE = null
        }
    }
}

Since you need the instance you have to save it somewhere, using a companion object seems like a reasonable solution to me.

If you somehow don't want to save the intance inside AppDatabase, you can also use an object (which is a singleton in Kotlin).

object AppDatabaseProvider {
    private var INSTANCE: AppDatabase? = null

    fun getInMemoryDatabase(context: Context): AppDatabase {
       // ...
    }

    fun destroyInstance() {
        INSTANCE = null
    }
}

These are both options to deal with static data in Kotlin, but you won't get it much shorter than that.

like image 100
Willi Mentzel Avatar answered Nov 25 '25 11:11

Willi Mentzel