使用Kotlin编码时,Dagger 2抛出编译错误

时间:2019-08-15 14:37:37

标签: android kotlin

使用Kotlin进行编码时,Dagger 2无法创建子组件对象。当我使用Java进行编码时,相同的代码运行良好

// MainActivityComponent:
@Subcomponent
interface MainActivityComponent : AndroidInjector<MainActivity> {
    @Subcomponent.Builder
    abstract class Builder : AndroidInjector.Builder<MainActivity>() {

    }
}

ActivityBindingModule:
@Module(subcomponents = [MainActivityComponent::class])
abstract class ActivityBindingModule {

    @Binds
    @IntoMap
    @ActivityKey(MainActivity::class)
    abstract fun getActivityInjectors(buider: MainActivityComponent.Builder): AndroidInjector.Factory<out Activity>
}

ActivityInjector:

class ActivityInjector @Inject constructor(val activityInjectors: Map<Class<out Activity>, Provider<AndroidInjector.Factory<out Activity>>>) {
    val cache = HashMap<String, AndroidInjector<out Activity>>()

    fun inject(activity: Activity) {
        if (activity !is BaseActivity) {
            throw IllegalArgumentException("activity must extend Base")
        }
        val instanceId = (activity as BaseActivity).getInstanceId()
        if (cache.containsKey(instanceId)) {
            val androidInjector = cache.get(instanceId) as AndroidInjector<Activity>
            androidInjector.inject(activity)
        } else {
            val androidInjectorFactory =
                activityInjectors.get(activity::class.java)?.get() as AndroidInjector.Factory<Activity>
            val androidInjector = androidInjectorFactory.create(activity)
            cache.put(instanceId, androidInjector)
            androidInjector.inject(activity)
        }
    }

    companion object {
        fun get(context: Context): ActivityInjector {
            return (context.applicationContext as MyApplication).getActivityInjectors()
        }
    }
}

我的应用程序:

   class MyApplication : Application() {
             @Inject
             lateinit var activityInjector: ActivityInjector

            lateinit var applicationComponent: ApplicationComponent

            override fun onCreate() {
                super.onCreate()
                applicationComponent = DaggerApplicationComponent.builder().applicaitonModule(ApplicaitonModule(this)).build()
                applicationComponent.inject(this)


            }
            fun getActivityInjectors(): ActivityInjector {
                return activityInjector
            }
        }

错误:

  

预期:应成功编译并提供适当的   依存关系       实际::错误:[Dagger / MissingBinding] java.util.Map ,?   没有提供扩展javax.inject.Provider >>   @提供注释的方法。

0 个答案:

没有答案