I was using def lifecycle_version = "2.3.1"
,
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
.
but I had to update version to def lifecycle_version = "2.4.0-alpha03"
to use some features, but ViewModelProvider.Factory
class doesn't work after I use def lifecycle_version = "2.4.0-alpha03"
.
class ViewModelFactory(private val param:String,private val param2: String) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return if (modelClass.isAssignableFrom(ReviewViewModel::class.java)) {
ReviewViewModel(param,param2) as T
}else if(modelClass.isAssignableFrom(FoodViewModel::class.java)){
FoodViewModel(param,param2) as T
else {
throw IllegalArgumentException()
}
}
}
the error messages are
! Class 'ViewModelFactory' is not abstract and does not implement abstract member public abstract fun <T : ViewModel> create(modelClass: Class<T>): T defined in androidx.lifecycle.ViewModelProvider.Factory
! 'create' overrides nothing
Thanks..
CodePudding user response:
You've written:
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
But what the error message is saying is that create
must always have a non-null ViewModel
type. You need to change your method signature to remove the ?
that indicates nullability on your <T : ViewModel?>
:
override fun <T : ViewModel> create(modelClass: Class<T>): T {
This is specifically called out in the Lifecycle 2.4 release notes:
Source-breaking change:
ViewModelProvider
has been rewritten in Kotlin.ViewModelProvider.Factory.create
method now longer allows nullable generic.