Dagger: @JvmStatic in @Module companion object is not supported

Created on 24 Oct 2019  路  7Comments  路  Source: google/dagger

With the release of 2.25.2, @JvmStatic is not needed anymore for the @Module object classes, however we still have to use them for the @Module companion objects

Current solution example for avoiding it from companion objects:

@Module(includes = [FooModule.Static::class])
abstract class FooModule {
   @Binds
   abstract fun providesFoo() : Foo

   @Module
    object Static{
       @Provides
       fun providesFooStatic() : FooStatic
    }
}

All 7 comments

IIUC you're expected to move to using an object.

IIUC you're expected to move to using an object.

That is a solution, but would be good to support objects too. We dont always want to have multiple coupled modules with different naming

how are you trying to bind the companion object? the reference likely needs to be SomeFoo.Companion::class and not SomeFoo::class.

Additionally I am thinking that the semantics of a companion object should preclude it from being used as an @Module? Probably depends on ones interpretation?

companion objects require some discussion still, there's no formal support or recommendation one way or the other AFAIK. There's no expectation to move unless you were using companion objects as a separate module from the enclosing class.

This issue would be better framed as a place to discuss how they could be treated in Dagger.

Companion objects are useful when you want both @Binds and @Provides in the same module:

@Module
abstract class FeatureModule {
    @Binds
    abstract fun bindClassA(objectA: ClassA) : SuperclassOfA 

    @Module
    companion object {
        @Provides
        @JvmStatic
        fun provideClassB(): ClassB {
            TODO()
        }
    }
}

Without it, Dagger complains that A @Module may not contain both non-static and abstract binding methods

This caught me by surprise, though now I understand why companion objects are not the same. Still, I think the release notes should be adjusted to clarify this.

Companion objects are now supported in 2.26.

Was this page helpful?
0 / 5 - 0 ratings