我正在关注this tutorial,但现在我想将WordRepository类转换为kotlin。我对kotlin极为陌生,因此我尝试使用this online kotlin converter并从第一个链接复制粘贴的Java WordRepository类。下面是原始的Java代码btw:
public class WordRepository {
private WordDao mWordDao;
private LiveData<List<Word>> mAllWords;
WordRepository(Application application) {
WordRoomDatabase db = WordRoomDatabase.getDatabase(application);
mWordDao = db.wordDao();
mAllWords = mWordDao.getAllWords();
}
LiveData<List<Word>> getAllWords() {
return mAllWords;
}
public void insert (Word word) {
new insertAsyncTask(mWordDao).execute(word);
}
private static class insertAsyncTask extends AsyncTask<Word, Void, Void> {
private WordDao mAsyncTaskDao;
insertAsyncTask(WordDao dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(final Word... params) {
mAsyncTaskDao.insert(params[0]);
return null;
}
}
}
下面是我从在线转换器中获得的kotlin代码:
class WordRepository internal constructor(application:Application) {
private val mWordDao:WordDao
internal val allWords:LiveData<List<Word>>
init{
val db = WordRoomDatabase.getDatabase(application)
mWordDao = db.wordDao()
allWords = mWordDao.getAllWords()
}
fun insert(word:Word) {
insertAsyncTask(mWordDao).execute(word)
}
private class insertAsyncTask internal constructor(dao:WordDao):AsyncTask<Word, Void, Void>() {
private val mAsyncTaskDao:WordDao
init{
mAsyncTaskDao = dao
}
protected fun doInBackground(vararg params:Word):Void {
mAsyncTaskDao.insert(params[0])
return null
}
}
}
请注意,为了使上面的代码有效,我进行了更改
WordRoomDatabase.getDatabase(application)
到
WordRoomDatabase.getInstance(application)
因为我也将WordRoomDatabase更改为kotlin,并且它不再具有getDatabase函数。这是WordRoomDatabase的外观
abstract class WordRoomDatabase: RoomDatabase(){
companion object {
private var INSTANCE: WordRoomDatabase? = null
fun getInstance(context: Context): WordRoomDatabase? {
if (INSTANCE == null){
synchronized(WordRoomDatabase::class){
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
WordRoomDatabase::class.java, "sps.db")
.build()
}
}
return INSTANCE
}
fun destroyInstance(){
INSTANCE == null
}
}
}
但是,代码不起作用,特别是这一部分:
mWordDao = db.wordDao();
显示错误
仅允许在服务器上安全(?。)或非空声明(!!。)的调用 AppDatabase类型的可为空的接收器?
答案 0 :(得分:1)
这里的问题是,由于WordRoomDatabase.getInstance()
的签名,您将返回一个 nullable 实例(带问号的类型)。
您可以将getInstance
更改为:
fun getInstance(context: Context): WordRoomDatabase {
if (INSTANCE == null){
synchronized(WordRoomDatabase::class){
INSTANCE = when you call [https://kotlinlang.org/docs/reference/null-safety.html#safe-calls](https://kotlinlang.org/docs/reference/null-safety.html#safe-calls)Room.databaseBuilder(context.getApplicationContext(),
WordRoomDatabase::class.java, "sps.db")
.build()
}
}
return INSTANCE as WordRoomDatabase
}
要进一步了解可为null的类型和安全调用,请参见以下有用链接:
https://kotlinlang.org/docs/reference/null-safety.html#safe-calls
https://www.callicoder.com/kotlin-nullable-types-null-safety/