【问题标题】:Call super throws "super is not an expression"调用 super 会抛出“super 不是表达式”
【发布时间】: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


【解决方案1】:

你已经在这里调用了 super:NotesViewModel private constructor(application: Application) : AndroidViewModel(application)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    相关资源
    最近更新 更多