调用超级投掷"super is not an expression"



我在谷歌指南中学习了MVVM的实现:https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#8(发布了链接,特别是我感兴趣的页面(
由于我了解在Java中实现它,我决定改用Kotlin。在初始化扩展AndroidViewModel的类中的构造函数时,我需要调用super,它会引发以下错误:

"super'不是一个表达式,它只能在左侧使用点('.'(">

当我在谷歌上搜索并找到类似的主题时,我根本不明白,所以我没有解决我的问题。这是我为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);
}
}

您已经在此处调用super:NotesViewModel private constructor(application: Application) : AndroidViewModel(application)

另一个问题是您的构造函数是private

只需将其设为public并从init()中删除super调用

相关内容

最新更新