Dagger Kotlin限定符构造函数注入无效

时间:2018-09-08 17:22:39

标签: android kotlin dagger

我下面的模块带有带有限定符的@Provides方法

apps:
  - name: app1
    git_repo: https://github.com/philgyford/app1.git
    # ...
  - name: app2
    git_repo: https://github.com/philgyford/app2.git
    # ...

然后是我想通过构造函数和限定符将此列表注入到我的类中:

@Module
class VocabularyModule {

    @VocabularyProviders
    @Singleton
    @Provides
    fun provideVocabularies(): List<VocabularyProvider> {
        return listOf(
                AnimalsVocabularyProvider(),
                FamilyVocabularyProvider(),
                FoodVocabularyProvider(),
                NumberVocabularyProvider(),
                ColorsVocabularyProvider(),
                FreeTimeVocabularyProvider(),
                SportVocabularyProvider(),
                NatureVocabularyProvider(),
                PeopleVocabularyProvider(),
                TransportationVocabularyProvider()
        )
    }
}

@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class VocabularyProviders

我收到此错误,但一切看起来正确

class VocabularyFactory
@Inject constructor(@param:VocabularyProviders val providers: List<VocabularyProvider>) {

    fun getVocabulary(category: VocabularyCategory): Vocabulary {
        for (provider in providers) {
            if (category == provider.category) {
                return provider.vocabulary
            }
        }
        throw IllegalStateException("didn't find provider that could provide vocabulary of $category category")
    }

}

1 个答案:

答案 0 :(得分:2)

我继续翻阅类似的问题,并遇到了这个问题:Dagger 2 multibindings with Kotlin

因此,据我了解,kotlin编译器在参数中使用泛型类型“有点混乱”,这导致dagger无法链接它们。

我这样更改了工厂的构造函数以避免这种情况-addind @JvmSuppressWildcards批注:

class VocabularyFactory
@Inject constructor(@param:VocabularyProviders val providers:@JvmSuppressWildcards List<VocabularyProvider>) {
...
}

在此保留此问题,因为可能会有更多的人参加。