I am using new architecture components with Dagger2, and I would like to introduce my ViewModels using the Factory class. The Factory class itself is injective. All this works well when the Factory class is defined in Java, but when I convert it to Kotlin, Dagger2 does not know how to create a Map for the constructor, whereas in Java it knows how to do it. I assume the difference is that after the conversion, the Factory class uses the Map from the kotlin package, and not from the java.util.Map package. How can I get Dagger2 to create a map for the Factory constructor?
Here is the factory class
@ActivityScope class MainActivityViewModelFactory @Inject constructor(private val creators: Map<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { var creator: Provider<out ViewModel>? = creators[modelClass] if (creator == null) { for ((key, value) in creators) { if (modelClass.isAssignableFrom(key)) { creator = value break } } } if (creator == null) { throw IllegalArgumentException("unknown model class " + modelClass) } try { return creator.get() as T } catch (e: Exception) { throw RuntimeException(e) } } }
and this is a mistake
Error:java.util.Map<java.lang.Class<? extends android.arch.lifecycle.ViewModel>,? extends javax.inject.Provider<android.arch.lifecycle.ViewModel>> cannot be provided without an @Provides-annotated method.
I tried to create a module for providing a map, but that did not help.
@ActivityScope @Module class MapModule { @Provides fun provideMap(): Map<Class<out ViewModel>, Provider<ViewModel>> = mutableMapOf() }
source share