I have a simple class as below

class MainString(val msg: String)

我想给它注入不同的参数,所以我按照https://google.github.io/dagger/users-guide中所示的指南使用@Named限定符

With that my AppModule has

@Provides @Named("Two")
fun provideTwoMainString(): MainString {
    return MainString("Two")
}

@Provides @Named("One")
fun provideOneMainString(): MainString {
    return MainString("One")
}

在我的MainActivity中,我只需呼叫

@Inject @Named("One")
lateinit var stringOne: MainString

@Inject @Named("Two")
lateinit var stringTwo: MainString

然而,当我编译时,它会抱怨

Error:(11, 1) error: com.elyeproj.demo_dagger_scope.MainString cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.

It seems to want me to provide another Provider without the qualifier. So if I add the below, all will compiles. But it is not of used to me, as I want to have different argument injection.

@Provides
fun provideMainString(): MainString {
    return MainString("Solo")
}

What have I done wrong?

推荐答案

kotlin的注释工作略有不同.看this doc

You have to annotate the field as:

@Inject @field:Named("Two")
lateinit var stringOne: MainString

Kotlin相关问答推荐

测试Compose Multiplatform UI时,为另一个文件设置ComposeRule()

用普通Kotlin理解Gradle的Kotlin DSL'""

Jetpack Compose Material3和Material2 Slider onValueChangeFinded()的行为不同

如何编写带有依赖项的自定义Kotlin串行化程序?

如何接受任何派生类KClass

Kotlin:将泛型添加到列表任何>

捕捉异常是Kotlin协程中的反模式吗?

合并状态流

mutableStateOf 和 mutableStateListOf 有什么区别?

如何创建扩展函数isNullOrEmpty?

如何将glide显示的图像下载到设备存储中.Kotlin

匹配在单词边界上包含特殊字符的变量字符串的正则表达式

类型不匹配:Required: Context, Found: Intent

判断 AAR 元数据值时发现的一个或多个问题:

kotlin,如何从函数返回类类型

`this@classname` 在 Kotlin 中是什么意思?

包括登录Elvis operator?

Jetpack Compose – LazyColumn 不重组

使用范围的稀疏sparse值列表

如何启用spring security kotlin DSL?