首页 > 解决方案 > Dagger 2 Set Multibinding 不适用于 Kotlin 中的 SimpleEntry?

问题描述

当提供Pairas时,以下多重绑定有效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
    }

但是,当变成 时PairSimpleEntry它不再起作用。

    @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

请注意,如果我使用Entryfor Java,它可以正常工作。仅不适用于 Kotlin。

标签: kotlindagger-2multibinding

解决方案


看起来我需要@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
    }

推荐阅读