in android ~ read.

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

When using kotlin and dagger2, Dagger 2's @Qualifier is used to specify the object.


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

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

@Module
class MainModule {

    @Provides
    @Named("red")
    fun getRedCloth() : Cloth {
        var cloth = Cloth()
        cloth.color="RED"
        return cloth;
    }
    
    @Provides
    @Named("black")
    fun getBlueCloth() : Cloth {
        var cloth = Cloth()
        cloth.color="BLACK"
        return cloth;
    }

The result is wrong

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

After searching for a long time, the reason for the problem is that when the
variable cloth code is compiled into Java bytecode, it will correspond to three target elements. One is the variable itself, and there are getters and setters.

Kotlin does not know that the annotation of this variable should be used. To solve this you need to use the annotation target keyword provided by Kotlin to tell Kotlin compiler that the target is the named field. In the above example you need to apply the annotation to the variable, so use the field keyword:


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