我收到以下错误:
Error:(8, 1) error: java.lang.String cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.
我一直在尝试制作一个提供两个合格字符串的模块。这是 Dagger 的简化设置。
@Singleton
@Component(modules = [GreetingsModule::class])
interface AppComponent {
fun inject(activity: MainActivity)
}
@Qualifier annotation class Spanish
@Qualifier annotation class French
@Qualifier annotation class English
@Module
@Singleton
class GreetingsModule {
@Provides
@Spanish
fun providesHola(): String = "Hola mundo! - From Dagger"
@Provides
@English
fun providesHello(): String = "Hello world! - From Dagger"
}
注入(inject)是在 MainActivity 中完成的:
class MainActivity : AppCompatActivity() {
@Inject @Spanish
lateinit var holaMundoText: String
@Inject @English
lateinit var helloWorldText: String
}
我也尝试直接在组件中声明 getter,但失败并出现同样的错误。将模块方法声明为静态时也是如此。
正如应该的那样,代码只使用一个 @Provide
就可以正常工作,然后将字符串注入(inject)到两个字段中。我认为问题出在限定符上。
非常感谢任何帮助。
使用:
- Android Studio 3.0.1
- Kotlin 1.2.10
- Dagger 2.14.1
最佳答案
使用 JSR-330 + Kotlin(Dagger2 是这种方法的一个实现)进行限定和命名注入(inject)存在一些问题。通过最近查看 Github 上 Dagger2 项目的积压工作,我知道 Google 团队希望在即将发布的版本中提供更主动的帮助/更有用的错误消息(无时间表)。
您缺少的是 @field:<Qualifier>
annotation use-type targets如链接文档中所述。所以试试吧;
@Inject @field:Spanish lateinit var holaMundoText: String
关于android - Kotlin + Dagger2 : cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48103894/