Search code examples
androiddependency-injectionscopesingletondagger-hilt

Does @Singleton in @Binds has any effect during dependency injection in hilt?


I have an interface

interface TestInterface{
    fun test()
}

and its implementation

class TestInterfaceImpl @Inject constructor(): TestInterface{
    override fun test(){}
}

To inject the TestInterfaceImpl, I created the following Module

@Module
@InstallIn(SingletonComponent::class)
object Module{ 
   @Singleton
   @Binds
   fun providesImplementation(testImpl: TestInterfaceImpl): TestInterface
}

The injected implementation is not singleton even if I annotate providesImplementation() with @Singleton.

However, If I declare TestInterfaceImpl as @Singleton in class declaration, the injected implementation is singleton..

@Singleton
class TestInterfaceImpl @Inject constructor(): TestInterface{
    override fun test(){}
}

Does @Singleton have any effect with @Binds in module? if not, should not hilt throw warning stating @Singleton not necessary when you are using @Binds?


Solution

  • @Singleton on @Binds TestInterface and TestInterfaceImpl have have different effects.

    @Singleton on @Binds TestInterface makes TestInterface instance singleton, not TestInterfaceImpl.

    If something requests TestInterface instance, Dagger Hilt will provide the singleton on TestInterface. But, when requesting TestInterfaceImpl, new instance of it will be created and provided.