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
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With