英文:
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<String, CommandHandler>
): 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<java.lang.String,? extends CommandHandler> 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<String, CommandHandler>
): 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>;
英文:
Map
in Kotlin is covariant (variance) on its value type (public interface Map<K, out V>
), but Map
in Java is not. Your function will be translated to
Config provideHubsConfig(Map<String, ? extends CommandHandler> commandRegistry) { ... }
but dagger provides exactly Map<String, CommandHandler>
. So we need to suppress wildcards with @JvmSuppressWildcards
commandRegistry: Map<String, @JvmSuppressWildcards CommandHandler>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论