Dagger2 @Binds 方法的参数类型必须可分配给具有接口和实现的 return 类型

Dagger2 @Binds methods' parameter type must be assignable to the return type with interface and implementation

我有一个 class 实现了接口 java.util.function.Function,我想将其注入另一个 class 使用 Dagger2:

class MyUsefulClass @Inject constructor() : Function<List<String>, String> {

    override fun apply(lines: List<String>): String {
        // Do stuff 
        return ""
    }
}

通常,我会在模块 class 中声明一个 @Binds 声明,如下所示:

@Module
interface MyModule {

    @Binds
    fun provideMyUsefulClass(concretion: MyUsefulClass): Function<List<String>, String>
}

这种方法对我在我的项目中实现此接口的所有其他 classes 非常有用,但在这个 one 实例中,我受到欢迎通过错误消息:

@Binds methods' parameter type must be assignable to the return type…

有趣的是,将 class 的 return 类型和 @Binds 声明从 Function<List<String>, String> 更改为 Function<MutableList<String>, String> 有效,并且一切都可以正常编译。

我在这里错过了什么?错误消息显然是不真实的。有没有我不知道的大问题?

我怀疑这可能是 "missing" @JvmSuppressWildcards 的情况,kotlin 在 List 类型中添加了一些 ? extends String 并且这使得匕首编译器失败(错误消息应该包含更多提示)。

我想您需要在使用它的地方将函数类型更改为 Function<List<@JvmSuppressWildcards String>, String>

这是一个众所周知的烦恼,您可以在此处阅读更详细的内容: https://medium.com/@naturalwarren/dagger-kotlin-3b03c8dd6e9b

我怀疑 MutableList 没有这个问题,因为你可以同时使用 'read' 和 'write' 字符串。