调用 super throws "super is not an expression"
Call super throws "super is not an expression"
我从 Google 指南开始学习实现 MVVM:
https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#8(发布 link 特别是我感兴趣的页面)。
因为我了解在 Java 中实现它,所以我决定切换到 Kotlin。
在 class 中初始化构造函数时扩展 AndroidViewModel
我需要调用 super
并且它会抛出以下错误:
"super' is not an expression it can only be used on the left-hand side
of a dot ('.')"
当我用谷歌搜索并找到类似的 但我完全不理解所以我没有解决我的问题。
这是我 ViewModel
class:
的代码
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,构造构造器呢?
这是此 class:
的正确 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
调用
我从 Google 指南开始学习实现 MVVM:
https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#8(发布 link 特别是我感兴趣的页面)。
因为我了解在 Java 中实现它,所以我决定切换到 Kotlin。
在 class 中初始化构造函数时扩展 AndroidViewModel
我需要调用 super
并且它会抛出以下错误:
"super' is not an expression it can only be used on the left-hand side of a dot ('.')"
当我用谷歌搜索并找到类似的 ViewModel
class:
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,构造构造器呢? 这是此 class:
的正确 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
调用