Sobes.tech
Junior — Middle

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:

  • @Provides is 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();
    }
    
  • @Binds is 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 @Binds must be abstract and simply return the interface.

    @Binds
    abstract MyInterface bindMyInterface(MyImplementation impl);
    

Key differences:

  • @Provides allows writing logic to create the object.
  • @Binds simply 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.