Junior — Middle
What is the difference between the Binds and Provides annotations in Dagger and when is each better to use?
sobes.tech AI
Answer from AI
In Dagger, the annotations @Binds and @Provides are used to specify how to create dependencies, but they are applied in different cases:
-
@Provides — is used on methods in modules that contain logic for creating an object. You can write any code, create the object manually, call constructors, perform calculations.
-
@Binds — is used to bind an interface to a specific implementation. A method with @Binds must be abstract and simply return the implementation of the interface. This is a more optimal and concise way when you have a ready-made class with an @Inject constructor.
When to use:
- If the implementation is simple and the class has an @Inject constructor, it is better to use @Binds to bind the interface to the implementation.
- If creating the object requires complex logic, parameters, or external calls, use @Provides.
Example of @Binds:
@Module
abstract class MyModule {
@Binds
abstract MyInterface bindMyInterface(MyImplementation impl);
}
Example of @Provides:
@Module
class MyModule {
@Provides
MyInterface provideMyInterface() {
return new MyImplementation("param");
}
}