Sobes.tech
Junior — Middle

In what cases is the use of the @Binds annotation inadmissible or impractical?

sobes.tech AI

Answer from AI

The @Binds annotation in Dagger is used to bind an interface to its implementation through an abstract method in a module. However, there are situations where its use is not allowed or not advisable:

  • When you need to create an object using a constructor with parameters, rather than simply binding an interface to a specific class. In this case, it's better to use @Provides with a method that creates the object.
  • If you need to perform additional logic when creating the dependency (e.g., configuration, calculations), @Binds is not suitable because it only binds types.
  • When the bound class is not an interface or abstract class, but a concrete class without an interface.

@Binds only works with abstract methods and requires that the implementation be provided via a constructor with @Inject or another method.

Example where @Binds is not suitable:

@Module
abstract class NetworkModule {
    // Cannot use @Binds if creation logic is needed
    @Provides
    fun provideRetrofit(): Retrofit {
        return Retrofit.Builder()
            .baseUrl("https://example.com")
            .build()
    }
}

In such cases, @Provides is preferable.

In what cases is the use of the @Binds annotation… - sobes.tech