Why the dagger graph works works in java but in Kotlin it says missing Provides when I have provided?

huangapple go评论79阅读模式
英文:

Why the dagger graph works works in java but in Kotlin it says missing Provides when I have provided?

问题

我在将Dagger接口从Java转换为Kotlin时遇到了一些问题

我得到了[Dagger/MissingBinding] java.util.Map<java.lang.String,? extends CommandHandler>,如果没有@Provides注释的方法,无法提供。

以下是我的接口

interface TopicConfigModule {
    @Binds
    @IntoMap
    @StringKey(NAME)
    fun bindCommandHandler(handler: TopicCommandHandler): CommandHandler
    
    companion object {
        @JvmStatic
        @Provides
        @FragmentScope
        fun provideHubsConfig(
            commandRegistry: Map&lt;String, CommandHandler&gt;
        ): Config {
            return ...
        }
    }
}

而CommandHandler是Java接口

public interface HubsCommandHandler {```}


<details>
<summary>英文:</summary>

I have some issues when converting dagger interfaces from java to Kotlin 

I got [Dagger/MissingBinding] java.util.Map&lt;java.lang.String,? extends CommandHandler&gt; cannot be provided without an @Provides-annotated method.


Here is my interface 


       interface TopicConfigModule {
        @Binds
        @IntoMap
        @StringKey(NAME)
        fun bindCommandHandler(handler: TopicCommandHandler): CommandHandler
        
        companion object {
            @JvmStatic
            @Provides
            @FragmentScope
            fun provideHubsConfig(
                commandRegistry: Map&lt;String, CommandHandler&gt;
            ): Config {
                return ...
            }
        }
    }

and CommandHandler is java interface 

public interface HubsCommandHandler {```}

答案1

得分: 4

Map 在 Kotlin 中是协变的(协变性)其值类型为 (public interface Map<K, out V>),但在 Java 中的 Map 不是。你的函数将被翻译成

Config provideHubsConfig(Map<String, ? extends CommandHandler> commandRegistry) { ... }

但是 Dagger 提供的确切是 Map<String, CommandHandler>。所以我们需要使用 @JvmSuppressWildcards 来抑制通配符:

commandRegistry: Map<String, @JvmSuppressWildcards CommandHandler>;

从 Java 调用 Kotlin - 协变泛型

英文:

Map in Kotlin is covariant (variance) on its value type (public interface Map&lt;K, out V&gt;), but Map in Java is not. Your function will be translated to

Config provideHubsConfig(Map&lt;String, ? extends CommandHandler&gt; commandRegistry) { ... }

but dagger provides exactly Map&lt;String, CommandHandler&gt;. So we need to suppress wildcards with @JvmSuppressWildcards

commandRegistry: Map&lt;String, @JvmSuppressWildcards CommandHandler&gt;

Calling Kotlin from Java - variant-generics

huangapple
  • 本文由 发表于 2020年5月5日 02:02:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/61598709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定