Dagger 2 static provider methods in kotlin

佐手、 提交于 2019-11-28 07:10:02

I can't test it right now, but I think this should work:

@Module
object AModule {
    @JvmStatic
    @Provides
    fun providesA(): A = A()
}
Omar Al Halabi

Although I think zsmb13's solution is better, I found another solution which works

@Module
class AModule {
  @Module
  companion object {
    @JvmStatic
    @Provides
    fun providesA(): A = A()
  }

  // add other non-static provides here
}

However, note that there will be two generated classes: AModule_ProvidesAFactory and AModule_Companion_ProvidesAFactory rather than the one AModule_ProvidesAFactory class for the case with an object instead of a class with a companion object

A great explanation which seems to be Google-approved is at https://github.com/google/dagger/issues/900

Specifically, see:

Static provides can be achieved via @JvmStatic. There are two scenarios I see this come up:

top-level objects

@Module object DataModule {   
  @JvmStatic @Provides fun 
    provideDiskCache() = DiskCache() 
} 

If you have an existing class module, things get a bit weirder

@Module abstract class DataModule {   
    @Binds abstract fun provideCache(diskCache: DiskCache): Cache

    @Module   
    companion object {
        @JvmStatic @Provides fun provideDiskCache() = DiskCache()   
    } 
} 

The way this works is as follows:

the companion object must also be annotated as @Module under the hood, the kotlin compiler will duplicate those static provides methods into the DataModule class. Dagger will see those and treat them like regular static fields. Dagger will also see them in the companion object, but that "module" will get code gen from dagger but be marked as "unused". The IDE will mark this as such, as the provideDiskCache method will be marked as unused. You can tell IntelliJ to ignore this for annotations annotated with @Provides via quickfix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!