我想使用Dagger 2提供一个函数作为依赖: @Moduleclass DatabaseModule { @Provides @Singleton fun provideDatabase(application: Application, betaFilter: (BetaFilterable) - Boolean): Database { return Database(application, BuildCon
@Module class DatabaseModule { @Provides @Singleton fun provideDatabase(application: Application, betaFilter: (BetaFilterable) -> Boolean): Database { return Database(application, BuildConfig.VERSION_CODE, betaFilter) } @Provides @Suppress("ConstantConditionIf") fun provideBetaFiler(): (BetaFilterable) -> Boolean { return if (BuildConfig.FLAVOR_audience == "regular") { { it.betaOnly.not() } } else { { true } } } }
不幸的是,它似乎不起作用:
[dagger.android.AndroidInjector.inject(T)] kotlin.jvm.functions.Function1<? super com.app.data.BetaFilterable,java.lang.Boolean> cannot be provided without an @Provides-annotated method.
我在这里错过了什么?
它不起作用,因为为了允许调用超类型的函数来代替lambda((Any) – >布尔值可以和(BetaFilterable) – >布尔)一起使用函数作为参数生成字节码到允许这个.以下代码:
object Thing fun provide(): (Thing) -> Boolean { TODO() } fun requires(func: (Thing) -> Boolean) { TODO() }
结果如下签名:
signature
()Lkotlin/jvm/functions/Function1<LThing;Ljava/lang/Boolean;>
;declaration:
kotlin.jvm.functions.Function1<Thing, java.lang.Boolean> provide()
signature
(Lkotlin/jvm/functions/Function1<-LThing;Ljava/lang/Boolean;>;)V
declaration:
void requires(kotlin.jvm.functions.Function1<? super Thing, java.lang.Boolean>)
-LThing(?super Thing)和LThing(Thing)之间的细微差别使得这些类型与Dagger不兼容.
我不相信有可能使这项工作,你需要定义一个不相同的单独的接口?超/?像Function1一样扩展属性.