当提供Pair
作为IntoSet
时,以下多绑定有效
@Provides
@IntoSet
fun entryOne(): Pair<String, String> {
val key = randomStringGenerator()
val value = "Random Value 1"
return Pair(key, value)
}
@Provides
@IntoSet
fun entryTwo(): Pair<String, String> {
val key = randomStringGenerator()
val value = "Random Value 2"
return Pair(key, value)
}
@Provides
fun randomKeyValueMap(entries: Set<Pair<String, String>>): Map<String, String> {
val randomKeyValueMap = LinkedHashMap<String, String>(entries.size)
for (entry in entries) {
randomKeyValueMap[entry.first] = entry.second
}
return randomKeyValueMap
}
然而,当把Pair
变成SimpleEntry
时,它就不起作用了。
@Provides
@IntoSet
fun entryOne(): AbstractMap.SimpleEntry<String, String> {
val key = randomStringGenerator()
val value = "Random Value 1"
return AbstractMap.SimpleEntry(key, value)
}
@Provides
@IntoSet
fun entryTwo(): AbstractMap.SimpleEntry<String, String> {
val key = randomStringGenerator()
val value = "Random Value 2"
return AbstractMap.SimpleEntry(key, value)
}
@Provides
fun randomKeyValueMap(entries: Set<AbstractMap.SimpleEntry<String, String>>): Map<String, String> {
val randomKeyValueMap = LinkedHashMap<String, String>(entries.size)
for (entry in entries) {
randomKeyValueMap[entry.key] = entry.value
}
return randomKeyValueMap
}
它抱怨
error: [Dagger/MissingBinding] java.util.Set<? extends java.util.AbstractMap.SimpleEntry<java.lang.String,java.lang.String>> cannot be provided without an @Provides-annotated method.
public abstract interface MyComponent {
^
java.util.Set<? extends java.util.AbstractMap.SimpleEntry<java.lang.String,java.lang.String>> is injected at
请注意,如果我将Entry
用于Java,它可以正常工作。只是对科特林不起作用。
看起来我需要@JvmSuppressWildcards
@Provides
@IntoSet
fun entryOne(): Map.Entry<String, String> {
val key = randomStringGenerator()
val value = "Random Value 1"
return AbstractMap.SimpleEntry(key, value)
}
@Provides
@IntoSet
fun entryTwo(): Map.Entry<String, String> {
val key = randomStringGenerator()
val value = "Random Value 2"
return AbstractMap.SimpleEntry(key, value)
}
@Provides
@JvmSuppressWildcards
fun randomKeyValueMap(entries: Set<Map.Entry<String, String>>): Map<String, String> {
val randomKeyValueMap = LinkedHashMap<String, String>(entries.size)
for (entry in entries) {
randomKeyValueMap[entry.key] = entry.value
}
return randomKeyValueMap
}