我提出了以下问题:
我的主要活动代码:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ...
// ERROR: Cannot create instance of an abstract class
var db = DataBase().getDataBase(this)
// ...
}
}
Room的数据库:
@Database(entities = arrayOf(DataBaseUser::class), version = 1)
abstract class DataBase : RoomDatabase() {
val DB_NAME : String = "DataBaseUser"
private lateinit var INSTANCE : DataBase
fun getDataBase(context: Context): DataBase {
if (INSTANCE == null){
INSTANCE = Room.databaseBuilder(context.applicationContext,DataBase::class.java,DB_NAME).build()
}
return INSTANCE
}
abstract fun getUserDao(): DataBaseUserDao
}
我无法在Kotlin中实例化该类。在Java中,我这样做了:
db = AppDataBase.getDataBase(view.getContext());
如何在Kotlin中获得相同的结果?
答案 0 :(得分:7)
使用单例(在Kotlin object
中)来保存Room数据库实例:
@Database(entities = arrayOf(DataBaseUser::class), version = 1)
abstract class DataBase : RoomDatabase() {
abstract fun getUserDao(): DataBaseUserDao
}
object DatabaseProvider {
val DB_NAME : String = "DataBaseUser"
private lateinit var INSTANCE : DataBase
fun getDataBase(context: Context): DataBase {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.applicationContext,DataBase::class.java,DB_NAME).build()
}
return INSTANCE
}
}
用法:
val db = DatabaseProvider.getDataBase(view.getContext())
答案 1 :(得分:1)
要在Kotlin中实例化抽象类,请使用object: <your class>
。
例如:
abstract class AbstractTest {
abstract fun someFun(): Int
}
fun main(args: Array<String>) {
val astractInstance = object : AbstractTest() {
override fun someFun(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
}
答案 2 :(得分:0)
您可以在下面使用
var db = object: DataBase(){
override fun getUserDao(): DataBase{
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}