1

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

ullas_jain
  • 13
  • 8
  • Got to know about Jake Wharton's comment on using `objects` instead https://github.com/google/dagger/issues/900#issuecomment-410041915 – ullas_jain Nov 05 '20 at 07:06

2 Answers2

1

Dagger 2.26 made it an error to include a companion object module in the modules parameter of @Component or @Subcomponent. Instead, companion objects are automatically included if the containing class is a module. Hilt's @InstallIn simply adds the annotated module to a generated component class, so you get the same error if you annotate a companion object with @InstallIn.

Remove @InstallIn (and @Module) from the companion object, and everything should work fine.

Nitrodon
  • 3,089
  • 1
  • 8
  • 15
0

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) 
 }

}
Saeid Lotfi
  • 2,043
  • 1
  • 11
  • 23