【发布时间】:2019-04-11 23:27:39
【问题描述】:
我从 Google 指南开始学习实施 MVVM:
https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#8(特别是我感兴趣的页面的发布链接)。
因为我了解用 Java 实现它,所以我决定改用 Kotlin。
在扩展AndroidViewModel 的类中初始化构造函数时,我需要调用super,它会引发以下错误:
"super' 不是一个表达式,它只能用在左边 一个点 ('.')"
当我用谷歌搜索并发现类似的topic 但我根本不理解它所以我没有解决我的问题。
这是我的ViewModel 类代码:
class NotesViewModel private constructor(application: Application) : AndroidViewModel(application){
var mRepository: NotesRepository? = null
var mAllNotes: LiveData<List<Notes>>? = null
init {
super(application) // <-- here it throws me an error
mRepository = NotesRepository(application)
mAllNotes = mRepository!!.getAllWords()
}
fun getAllNotes(): LiveData<List<Notes>>{
return mAllNotes!!
}
fun insert(notes: Notes){
mRepository!!.insert(notes)
}
}
那么,我应该如何正确调用super,构造一个构造函数呢? 这是该类的正确 java 代码:
public class WordViewModel extends AndroidViewModel {
private WordRepository mRepository;
private LiveData<List<Word>> mAllWords;
public WordViewModel(Application application) {
super(application);
mRepository = new WordRepository(application);
mAllWords = mRepository.getAllWords();
}
LiveData<List<Word>> getAllWords() {
return mAllWords;
}
void insert(Word word) {
mRepository.insert(word);
}
}
【问题讨论】:
标签: java android mvvm kotlin android-livedata