尝试使用dagger2时出现问题这是我的ViewModelFactory:
class ViewModelFactory @Inject constructor(
private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
val creator = viewModels[modelClass]
?: viewModels.asIterable().firstOrNull {
modelClass.isAssignableFrom(it.key)
}?.value ?: throw IllegalArgumentException("$UNKNOWN_MODEL_CLASS $modelClass")
return try {
@Suppress("UNCHECKED_CAST")
creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
当我将viewModels
更改为Map时,出现以下错误:
public abstract interface AppComponent {
^
java.util.Map<java.lang.Class<? extends androidx.lifecycle.ViewModel>,? extends javax.inject.Provider<androidx.lifecycle.ViewModel>> is injected at
com.example.baseproject.utils.ViewModelFactory(viewModels)
com.example.baseproject.utils.ViewModelFactory is injected at
com.example.baseproject.di.ViewModelBuilder.bindViewModelFactory(viewModelFactory)
androidx.lifecycle.ViewModelProvider.Factory is injected at
com.example.baseproject.MainActivity.viewModelFactory
com.example.baseproject.MainActivity is injected at
dagger.android.AndroidInjector.inject(T) [com.example.baseproject.di.AppComponent → com.example.baseproject.di.ActivityModules_ContributeMainActivity.MainActivitySubcomponent]
请帮助我,我不知道为什么会发生
您缺少@JvmSuppressWildcards
。您想获得一个Provider<ViewModel>
,而不是Provider<? extends ViewModel>
,但是Kotlin会生成一个没有注释的Provider<? extends ViewModel>
。
private val viewModels: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>) : ViewModelProvider.Factory {