使用 Kotlin 进行 Dagger 2 多重绑定 [英] Dagger 2 multibindings with Kotlin

查看:36
本文介绍了使用 Kotlin 进行 Dagger 2 多重绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 dagger 2 模块中有以下代码片段

I have the following snippet in my dagger 2 module

@Singleton
@Provides
@ElementsIntoSet
fun providesQueries(foo: Foo): Set<Foo>{
    val queries = LinkedHashSet<Foo>()
    queries.add(foo)
    return queries
}

我尝试以这种方式注入

@Inject lateinit var foo: Set<Foo>

但 dagger 显示一个错误,指出 Dagger 无法在没有 @Provides 或 @Produces 方法的情况下提供 java.util.Set.

But dagger shows an error which says that Dagger cannot provides java.util.Set without @Provides or @Produces method.

我在 java 中做了同样的事情并且它起作用了.有人知道为什么会失败吗?

I did the same in java and it worked. Does somebody know why is it failing?

推荐答案

正如 Kotlin 中描述的那样 参考

As it described in the Kotlin reference

为了使 Kotlin API 在 Java 中工作,我们将 Box 生成为<代码>框 用于协变定义的 Box(或 Foo 用于逆变定义的 Foo) 当它作为参数出现时.

To make Kotlin APIs work in Java we generate Box<Super> as Box<? extends Super> for covariantly defined Box (or Foo<? super Bar> for contravariantly defined Foo) when it appears as a parameter.

您可以使用@JvmSuppressWildcards 来避免它,如下所示:

You can use @JvmSuppressWildcards for avoiding it, just as following:

@Inject lateinit var foo: Set<@JvmSuppressWildcards Foo>

这篇关于使用 Kotlin 进行 Dagger 2 多重绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆