Search code examples
androidkotlindagger-2dagger-hilt

Using Hilt @IntallIn for a dagger-2 module which has static provides method


While doing a dagger-2 to hilt migration, got this error for a module

Error:

FooModule.Companion is listed as a module, but it is a companion
object class. 
Add @Module to the enclosing class 
and reference that instead.

Before Hilt

@Module
abstract class FooModule {

 @Binds
 @FooScope
 abstract fun bindsManager(impl: FooManagerImpl): FooManager
 
 @Module
 companion object {
     
   @Provides
   @FooScope 
   @JvmStatic
   fun providesConfig(prefs: SharedPreferences): FooConfig = FooConfigImpl(prefs) 
 }

}

After Hilt

@InstallIn(ApplicationComponent::class)
@Module
abstract class FooModule {

 @Binds
 @FooScope
 abstract fun bindsManager(impl: FooManagerImpl): FooManager
 
 @InstallIn(ApplicationComponent::class)
 @Module
 companion object {
     
   @Provides
   @FooScope 
   @JvmStatic
   fun providesConfig(prefs: SharedPreferences): FooConfig = FooConfigImpl(prefs) 
 }

}

Migration doc reference: https://developer.android.com/codelabs/android-dagger-to-hilt#4


Solution

  • You need to change companion object to object

    @InstallIn(ApplicationComponent::class)
    @Module
    abstract class FooModule {
    
     @Binds
     @FooScope
     abstract fun bindsManager(impl: FooManagerImpl): FooManager
     
     @InstallIn(ApplicationComponent::class)
     @Module
     object AppModule{
         
       @Provides
       @FooScope 
       fun providesConfig(prefs: SharedPreferences): FooConfig = FooConfigImpl(prefs) 
     }
    
    }