Kotliin Dagger Field Injection in ViewModel Throws Dagger/Binding Exception

前端 未结 1 878
旧巷少年郎
旧巷少年郎 2021-01-15 06:18

I have followed this tutorial in order to do DI in my viewmodels. But I currently am stuck.

I have created a ViewModelFactory for my viewmodel which is as follows:

相关标签:
1条回答
  • 2021-01-15 06:56

    The error message indicates that the following code is wrong:

    fun providesHomeViewModelFactory(providerMap: Map<Class<out ViewModel>, Provider<ViewModel>>): HomeViewModelFactory {
        return HomeViewModelFactory(providerMap)
    }
    

    It should be

    fun providesHomeViewModelFactory(providerMap: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>): HomeViewModelFactory {
        return HomeViewModelFactory(providerMap)
    }
    

    It is because the signature of Map interface is Map<K, out V>, that means the Map<..., Provider<ViewModel>> will be compiled to Map<..., ? extends Provider<ViewModel>> Java code, so you are asking dagger for latter one but it only has former one in its object graph, then the compiler throws you the error.

    0 讨论(0)
提交回复
热议问题