我有以下定义:
@Module
class WeaverDataModule {
// Provide the three pumps from providers
// All of them still explicitly mark 'Pump' as their return type
@Provides @IntoSet fun providesPump(thermosiphon: Thermosiphon) : Pump = thermosiphon
@Provides @IntoSet fun providesAnotherPump(suctionBased: SuctionBased) : Pump = suctionBased
@Provides @IntoSet fun providesGenericPump(genericPump: GenericPump) : Pump = genericPump
}
@Component(modules = [WeaverDataModule::class])
interface WeaverData {
// Get the CoffeeMaker
fun coffeeMaker(): CoffeeMaker
// Get the list of pumps
fun getPumps() : Set<Pump>
}
interface Pump
// The three pumps
class Thermosiphon @Inject constructor(val heater: Heater) : Pump
class SuctionBased @Inject constructor() : Pump
class GenericPump @Inject constructor() : Pump
// Some random heater
class Heater @Inject constructor()
在我的代码中,当我执行以下操作时:
val cm = DaggerWeaverData.builder().build().getPumps()
我确实得到了预期的三个泵。但是,当我尝试将其注入其他类时:
class CoffeeMaker @Inject constructor(
private val heater: Heater,
private val pump: Set<Pump>
) {
fun makeCoffee() =
"Making coffee with heater ${heater::class.java} and using pumps" +
" ${pump.map { it::class.java }.joinToString(",")}"
}
我收到以下错误:
e: .../WeaverData.java:7: error: [Dagger/MissingBinding] java.util.Set<? extends weaver.Pump> cannot be provided without an @Provides-annotated method.
public abstract interface WeaverData {
^
java.util.Set<? extends weaver.Pump> is injected at
weaver.CoffeeMaker(…, pump)
weaver.CoffeeMaker is provided at
weaver.WeaverData.coffeeMaker()
我也尝试注入Collection<Pump>
,但仍然遇到类似的错误。在dagger docs on multibinding中,示例(在Java中)显示以下内容:
class Bar {
@Inject Bar(Set<String> strings) {
assert strings.contains("ABC");
assert strings.contains("DEF");
assert strings.contains("GHI");
}
}
这正是我在做什么。对于基于构造函数的注入,它在Kotlin中运行良好,因为以下代码可以按预期编译并运行:
class CoffeeMaker @Inject constructor(
private val heater: Heater
) {
fun makeCoffee() =
"Making coffee with heater ${heater::class.java}"
}
所以我对如何使这种多重绑定起作用感到困惑。
答案 0 :(得分:0)
因此,您需要做的是:
class CoffeeMaker @Inject constructor(
private val heater: Heater,
private val pumps: Set<@JvmSuppressWildcards Pump>
) {
fun makeCoffee() =
"Making coffee with heater ${heater::class.java} with pumps ${pumps.map { it::class.java }.joinToString(",")}"
}
这是因为Set
在Kotlin中定义为Set<out E>
,而Java则将其翻译为Set<? extends Pump>
。从类型理论的角度来看,Set<? extends Pump>
与Set<Pump>
不同,因此Dagger(可能)拒绝将Set<Pump>
视为Set<? extends Pump>
的注射剂,这是公平而正确的行为。
我们遇到的问题是,对于这些集合中的任何一个,由于默认情况下它们都是不可变的,因此类型为Set<X>
的声明将转换为Set<? extends X>
,因为不可变的集合仅具有对已解析的引用。收益类型,因此是协变的。为了验证该理论,以下内容也适用:
class CoffeeMaker @Inject constructor(
private val heater: Heater,
private val pumps: MutableSet<Pump>
) {
fun makeCoffee() =
"Making coffee with heater ${heater::class.java} with pumps ${pumps.map { it::class.java }.joinToString(",")}"
}
请注意MutableSet
的使用,其定义为MutableSet<E> : Set<E> ...
。这可能不是我们应该使用的东西,因为我怀疑这个集合实际上是可变的。因此,我们需要的是kotlin编译器将Set<out E>
视为Set<E>
(在这种情况下,可分配性是有效的,反之则不行)。为此,我们使用@JvmSuppressWildcards
批注。我希望这可以帮助其他面临类似问题的人。