Dagger 2 @Provides不能应用于Kotlin中的静态函数吗?

时间:2019-01-05 07:27:48

标签: kotlin dagger-2

我有以下运行良好的Java代码

@Module(subcomponents = {MainActivityComponent.class})
abstract public class ActivityBuilder {

    @Provides
    @Singleton
    static Context provideContext(Application application) {
        return application;
    }

    @Binds
    @IntoMap
    @ClassKey(MainActivity.class)
    abstract AndroidInjector.Factory<?> bindMainActivity(MainActivityComponent.Builder builder);
}

当我将其转换为Kotlin

@Module(subcomponents = [MainActivityComponent::class])
abstract class ActivityBuilder {
    companion object {
        @Provides
        @Singleton
        fun provideContext(application: Application): Context {
            return application
        }
    }

    @Binds
    @IntoMap
    @ClassKey(MainActivity::class)
    abstract fun bindMainActivity(builder: MainActivityComponent.Builder): AndroidInjector.Factory<*>

}

我在声明静态功能上无法使用@Provides时出错。

error: @Provides methods can only be present within a @Module or @ProducerModule
    public final android.content.Context provideContext(@org.jetbrains.annotations.NotNull()
                                         ^  

我该如何解决?

1 个答案:

答案 0 :(得分:2)

显然,以下方法可行。

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

    @Module
    companion object {
        @JvmStatic
        @Provides
        @Singleton
        fun provideContext(application: Application): Context {
            return application
        }
    }

    @Binds
    @IntoMap
    @ClassKey(MainActivity::class)
    abstract fun bindMainActivity(builder: MainActivityComponent.Builder): AndroidInjector.Factory<*>

}