What are the differences between the Provides and Binds annotations in Dagger, and in which situations are they recommended?
sobes.tech AI
Answer from AI
In Dagger, the annotations @Provides and @Binds are used to specify how dependencies are created, but they differ in implementation and usage.
-
@Providesis applied to methods in modules and allows explicit description of object creation logic. It is a regular method that can contain arbitrary code, such as creating an object with parameters or performing additional actions. -
@Bindsis used to bind an interface to a specific implementation. A method with@Bindsmust be abstract and simply return the implementation of the interface. This is a more efficient way because it does not generate additional code for object creation, but simply informs Dagger that when the interface is requested, a specific class should be used.
Usage recommendations:
- Use
@Bindswhen you need to bind an interface to an implementation and the object can be created directly (e.g., via a constructor with@Inject). - Use
@Provideswhen object creation requires additional logic, parameters, or cannot use a constructor with@Inject.
Example:
@Module
abstract class MyModule {
@Binds
abstract MyInterface bindMyInterface(MyImplementation impl);
}
@Module
class MyModule {
@Provides
MyObject provideMyObject() {
return new MyObject("param");
}
}