gpt4 book ai didi

android - 在 android kotlin mvvm 中没有主构造函数就不可能进行父类(super class)型初始化

转载 作者:行者123 更新时间:2023-12-02 13:12:47 26 4
gpt4 key购买 nike

我正在尝试做的事情:

我正在尝试将 viewModel 链接到 Activity 中并在两者之间使用工厂

MainActivity.kt

KtMainActivityViewModelFactory    ktMainActivityViewModel = ViewModelProviders.of(this,ktMainActivityViewModelFactory).get(KtMainActivityViewModel::class.java)

KtMainActivityViewModelFactory.kt

class KtMainActivityViewModelFactory : ViewModelProvider.Factory {


private val movieRepository: MovieRepository
private val database: MoviesAppDatabase
private val dataservice: MovieDataService

@Inject
constructor(movieRepository: MovieRepository, database: MoviesAppDatabase, dataservice: MovieDataService) {
this.movieRepository = movieRepository
this.database = database
this.dataservice = dataservice
}


override fun <T : ViewModel> create(modelClass: Class<T>): T {
return KtMainActivityViewModelFactory(movieRepository, database, dataservice) as T
}


}

KtMainActivityViewModel.kt

class KtMainActivityViewModel : ViewModel() {


private val movieRepository: MovieRepository
private val database: MoviesAppDatabase
private val dataservice: MovieDataService


constructor(movieRepository: MovieRepository, database: MoviesAppDatabase, dataservice: MovieDataService) : super() {
this.movieRepository = movieRepository
this.database = database
this.dataservice = dataservice
}


}

错误: enter image description here

最佳答案

因为你只有一个构造函数,所以它应该是主要的:

class KtMainActivityViewModel(private val movieRepository: MovieRepository, private val database: MoviesAppDatabase, private val dataservice: MovieDataService) : ViewModel() { ... }

作为一个额外的好处,这样您还需要提及每个属性一次而不是 4 次。

请注意,您可以在正文中声明 private val movieRepository: MovieRepository

class KtMainActivityViewModel(movieRepository: MovieRepository, database: MoviesAppDatabase, dataservice: MovieDataService) : ViewModel() { 
private val _movieRepository: MovieRepository = movieRepository
...
}

但没有理由这样做。

当然这也适用于KtMainActivityViewModelFactory:

class KtMainActivityViewModelFactory @Inject constructor(private val movieRepository: MovieRepository, private val database: MoviesAppDatabase, private val dataservice: MovieDataService) : ViewModelProvider.Factory {

override fun <T : ViewModel> create(modelClass: Class<T>): T {
return KtMainActivityViewModelFactory(movieRepository, database, dataservice) as T
}

}

关于android - 在 android kotlin mvvm 中没有主构造函数就不可能进行父类(super class)型初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57092550/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com