如何在Kotlin中实例化一个抽象类?
我想出了以下问题:
我的主活动代码:
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // ... // ERROR: Cannot create instance of an abstract class var db = DataBase().getDataBase(this) // ... } }
房间数据库:
@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中得到相同的结果?
使用单身(在Kotlin object
)来保存房间数据库实例:
@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())
为了在Kotlin中实例化抽象类,你可以使用object:
。 例:
abstract class AbstractTest { abstract fun someFun(): Int } fun main(args: Array) { val astractInstance = object : AbstractTest() { override fun someFun(): Int { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } } }
你可以在下面使用
var db = object: DataBase(){ override fun getUserDao(): DataBase{ TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }