cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method

在用kotlin和dagger2的时候,用到了Dagger 2 的 @Qualifier来指定对象

 class MainActivity : AppCompatActivity (){
    @Inject
    @Named("red")
    lateinit var cloth:Cloth
}
@Module
class MainModule {

    @Provides
    @Named("red")
    fun getRedCloth() : Cloth{
        var cloth = Cloth()
        cloth.color="红色"

        return cloth;
    }
    @Provides
    @Named("blue")
    fun getBlueCloth() : Cloth{
        var cloth = Cloth()
        cloth.color="蓝色"

        return cloth;
    }

结果报错了

cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method

搜了半天,出现问题的原因是
变量cloth这行代码编译为 Java 字节码的时候会对应三个目标元素,一个是变量本身、还有 getter 和 setter,Kotlin 不知道这个变量的注解应该使用到那个目标上。
要解决这个方式,需要使用 Kotlin 提供的注解目标关键字来告诉 Kotlin 所注解的目标是那个,上面示例中需要注解应用到 变量上,所以使用 field 关键字:

 class MainActivity : AppCompatActivity (){
    @Inject
    @field:Named("red")
    lateinit var cloth:Cloth
}

就好了

你可能感兴趣的:(cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method)