我是Kotlin的新手。 这是我想在kotlin中将其转换的Java代码
public class FavouritesViewModel extends AndroidViewModel {
private FavouritesDBHelper mFavHelper;
private ArrayList<Favourites> mFavs;
FavouritesViewModel(Application application) {
super(application);
mFavHelper = new FavouritesDBHelper(application);
}
}
但是我在构造函数中遇到了编译时错误
编码我的尝试:
public class FavoritesDataViewModel:ViewModel{
private lateinit var mFavHelper: DatabaseHelper
private lateinit var mfav:ArrayList<Favorites>
public constructor(application: Application): super(application){
mFavHelper = DatabaseHelper(application)
}
}
在super(application)
处出错
谢谢
答案 0 :(得分:0)
public class FavoritesDataViewModel:AndroidViewModel{
private lateinit var mFavHelper: DatabaseHelper
private lateinit var mfav:ArrayList<Favorites>
public constructor(application: Application): super(application){
mFavHelper = DatabaseHelper(application)
}
}
这解决了我的问题,我使用的是AndroidViewModel
而不是ViewModel
答案 1 :(得分:0)
public class FavoritesDataViewModel(application: Application):AndroidViewModel(application){
private var mFavHelper: DatabaseHelper
private lateinit var mfav:ArrayList<Favorites>
init{
mFavHelper = DatabaseHelper(getApplication<Application>())
}
public constructor(application: Application): super(application){
mFavHelper = DatabaseHelper(application)
}
}
这将帮助您调用超级调用以传递参数,并更安全地访问应用程序实例以用于viewModel。并帮助您避免使用latinit属性。