我正试图将变量从子类传递到父类的构造函数。
父类的构造函数由(Context!, String!, SQLiteDatabase.CursorFactory!, Int)
组成。
我可以轻松完成
class TodoListDBHandler(context: Context, databaseName: String, factory: SQLiteDatabase.CursorFactory, databaseVersion: Int):
SQLiteOpenHelper(context, databaseName, factory, databaseVersion)
但是我想直接在类内部指定数据库名称和版本,而不是每次调用构造函数时都指定它,因为这样可能会出错。
我当前的代码:
class TodoListDBHandler(context: Context, databaseName: String, factory: SQLiteDatabase.CursorFactory, databaseVersion: Int):
SQLiteOpenHelper(context, databaseName, factory, databaseVersion) {
val databaseFileName = "todoList.db"
val databaseVersion = 1
override fun onCreate(db: SQLiteDatabase?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
如上所述,我希望能够将我指定的变量传递给父级的构造函数。
编辑:这是所需的代码,但是使用Java
public TodoListDBHandler(Context context, SQLiteDatabase.CursorFactory factory) {
// databaseFileName and databaseVersion are already specified inside the class
super(context, databaseFileName, factory, databaseVersion)
}
答案 0 :(得分:3)
您可以直接在超类构造函数中传递常量参数。
class TodoListDBHandler(context: Context, factory: SQLiteDatabase.CursorFactory)
: SQLiteOpenHelper(context, "todoList.db", factory, 1) {
override fun onCreate(db: SQLiteDatabase) {
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
}
}
答案 1 :(得分:1)
@farhanjk提供了一个很好的解决方案,但您也可以将它们放入伴随对象中:
class TodoListDBHandler(context: Context, factory: SQLiteDatabase.CursorFactory):
SQLiteOpenHelper(context, TodoListDBHandler.databaseName, factory, TodoListDBHandler.databaseVersion) {
companion object {
val databaseFileName = "todoList.db"
val databaseVersion = 1
}
...
}
这可能很有用,例如如果是非平凡的初始化或仅创建一次列表等。