匕首@IntoSet 在 kotlin 对象中不起作用?

Mum*_*umi 0 kotlin dagger-2

我在https://google.github.io/dagger/multibindings 中使用了示例

模块 A

@Module
object MyModuleA {
    @Provides
    @IntoSet
    fun provideOneString(): String {
        return "ABC"
    }
}
Run Code Online (Sandbox Code Playgroud)

模块 B

@Module
object MyModuleB {
    @Provides
    @ElementsIntoSet
    fun provideSomeStrings(): Set<String> {
        return HashSet<String>(Arrays.asList("DEF", "GHI"))
    }
}
Run Code Online (Sandbox Code Playgroud)

成分

@Component(modules = [ MyModuleA::class, MyModuleB::class])
interface MyComponent {
    fun strings(): Set<String>
}
Run Code Online (Sandbox Code Playgroud)

测试

@Test
fun testMyComponent() {
    val myComponent = DaggerMyComponent.builder().build()
    println("${myComponent.strings()}")
}
Run Code Online (Sandbox Code Playgroud)

它显示必须设置 MyModuleA 的错误,但将模块从对象更改为类工作正常。

@Module
class MyModuleA {
    @Provides
    @IntoSet
    fun provideOneString(): String {
        return "ABC"
    }
}

@Module
class MyModuleB {
    @Provides
    @ElementsIntoSet
    fun provideSomeStrings(): Set<String> {
        return HashSet<String>(Arrays.asList("DEF", "GHI"))
    }
}
Run Code Online (Sandbox Code Playgroud)

@IntoSet 注释在 kotlin 对象中不起作用?

小智 6

我遇到了同样的问题,这个答案为我解决了。

使用 Kotlin 进行 Dagger 2 多重绑定

简而言之,您需要使用 Set<@JvmSuppressWildcards String> 代替,因为 kotlin 处理泛型中的类型变化的方式。