What is the difference between @Provides and @Binds annotations in the context of Dependency Injection?
sobes.tech AI
Answer from AI
In the context of Dependency Injection (DI) in Android (for example, with Dagger or Hilt), the annotations @Provides and @Binds are used to specify how dependencies are created, but they differ in method and application:
-
@Providesis applied to methods that create and return an object. These methods can contain arbitrary code to instantiate the object.@Provides MyInterface provideMyInterface() { return new MyImplementation(); } -
@Bindsis used to bind an interface to a specific implementation, but requires that the implementation is already provided elsewhere (for example, via a constructor with@Inject). The method with@Bindsmust be abstract and simply return the interface.@Binds abstract MyInterface bindMyInterface(MyImplementation impl);
Key differences:
@Providesallows writing logic to create the object.@Bindssimply binds the interface to an implementation without additional code.
Using @Binds is more efficient and preferred when the implementation is already available via a constructor, as it generates more optimized code.