【问题标题】:Dagger Kotlin qualifier constructor injection doesn't workDagger Kotlin 限定符构造函数注入不起作用
【发布时间】:2018-09-08 17:22:39
【问题描述】:

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

@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")
    }

}

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

11: error: [Dagger/MissingBinding] [dagger.android.AndroidInjector.inject(T)] @cz.ejstn.learnlanguageapp.core.dagger.module.vocabulary.VocabularyProviders java.util.List<? extends cz.ejstn.learnlanguageapp.vocabulary.model.factory.VocabularyProvider> cannot be provided without an @Provides-annotated method.

【问题讨论】:

  • 我已经解决了其他问题 - 发现在 Kotlin 中您需要指定注入的确切位置,翻阅 kotlinlang.org/docs/reference/… @param 似乎最适合我的问题,但它没有工作

标签: android kotlin dagger


【解决方案1】:

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

所以根据我的理解,kotlin 编译器在参数中使用泛型类型“有点混乱”,这导致 dagger 无法链接这些我猜。

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

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

在这里保留这个问题,因为更多的人可能会遇到这个问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 2015-11-11
    • 2018-07-04
    • 2019-02-23
    • 1970-01-01
    相关资源
    最近更新 更多