在用kotlin和dagger2的時(shí)候,用到了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="藍(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)問題的原因是
變量cloth這行代碼編譯為 Java 字節(jié)碼的時(shí)候會(huì)對應(yīng)三個(gè)目標(biāo)元素,一個(gè)是變量本身、還有 getter 和 setter,Kotlin 不知道這個(gè)變量的注解應(yīng)該使用到那個(gè)目標(biāo)上。
要解決這個(gè)方式,需要使用 Kotlin 提供的注解目標(biāo)關(guān)鍵字來告訴 Kotlin 所注解的目標(biāo)是那個(gè),上面示例中需要注解應(yīng)用到 變量上,所以使用 field 關(guān)鍵字:
class MainActivity : AppCompatActivity (){
@Inject
@field:Named("red")
lateinit var cloth:Cloth
}
就好了