在用kotlin和dagger2的時(shí)候向抢,用到了Dagger 2 的 @Qualifier來(lái)指定對(duì)象
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="藍(lán)色"
return cloth;
}
結(jié)果報(bào)錯(cuò)了
cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method
搜了半天策菜,出現(xiàn)問(wèn)題的原因是
變量cloth這行代碼編譯為 Java 字節(jié)碼的時(shí)候會(huì)對(duì)應(yīng)三個(gè)目標(biāo)元素丘损,一個(gè)是變量本身卿闹、還有 getter 和 setter阱高,Kotlin 不知道這個(gè)變量的注解應(yīng)該使用到那個(gè)目標(biāo)上鹦付。
要解決這個(gè)方式昆禽,需要使用 Kotlin 提供的注解目標(biāo)關(guān)鍵字來(lái)告訴 Kotlin 所注解的目標(biāo)是那個(gè)蝗蛙,上面示例中需要注解應(yīng)用到 變量上,所以使用 field 關(guān)鍵字:
class MainActivity : AppCompatActivity (){
@Inject
@field:Named("red")
lateinit var cloth:Cloth
}
就好了