无法提供类型为kolin lambda
的(Int) -> Unit
。但是可以提供() -> Unit
:-例如:-
@Module
class LambdaModule {
@Provides
fun getIntArgLambda(): (Int) -> Unit = {}
@Provides
fun getNoArgLambda(): () -> Unit = {}
@Provides
fun getRecyclerViewAdater(intLambda: (Int) -> Unit, noArg: () -> Unit): CustomAdapter = CustomAdapter(intLambda, noArg)
}
错误:-
[Dagger/MissingBinding] kotlin.jvm.functions.Function1<? super java.lang.Integer,kotlin.Unit> cannot be provided without an @Provides-annotated method.
但是,如果我不使用getIntArgLambda()
,它的工作原理是:-
@Provides
fun getRecyclerViewAdater(noArg: () -> Unit): CustomAdapter = CustomAdapter({}, noArg)
上面的代码正在工作:-
为什么我不能为同一
(Int) -> Unit
中的任何方法提供module
参数?
这是一个方差问题。它与Java通配符有关。
功能:
@Provides
fun getIntArgLambda(): (Int) -> Unit = {}
在Java中返回:
kotlin.jvm.functions.Function1<java.lang.Integer, kotlin.Unit>
而函数的参数intLambda
:
@Provides
fun getRecyclerViewAdater(intLambda: (Int) -> Unit, noArg: () -> Unit): CustomAdapter = CustomAdapter(intLambda, noArg)
在Java中是:
kotlin.jvm.functions.Function1<? super java.lang.Integer, kotlin.Unit>
要抑制通配符,您可以使用@JvmSuppressWildcards
:
@Module
class LambdaModule {
@Provides
fun getIntArgLambda(): (Int) -> Unit = {}
@Provides
fun getNoArgLambda(): () -> Unit = {}
@Provides
fun getRecyclerViewAdater(intLambda: Function1<@JvmSuppressWildcards Int, Unit>, noArg: () -> Unit): CustomAdapter = CustomAdapter(intLambda, noArg)
}