Sobes.tech
Junior — Middle

What is the difference between the Binds and Provides mechanisms in the context of dependency injection or modular systems?

sobes.tech AI

Answer from AI

In the context of dependency injection (for example, Dagger in Android), the annotations @Provides and @Binds serve different purposes, although both are used for dependency provision.

  • @Provides is used for methods that create and return a specific instance of an object. Usually, this is a method with a body where you can write logic to create the object.

  • @Binds is used to bind an interface to its implementation without creating a new instance. A method with @Binds must be abstract and simply return the implementation of the interface passed as a parameter.

Example:

@Module
abstract class NetworkModule {
    @Binds
    abstract fun bindApiService(impl: ApiServiceImpl): ApiService
}

@Module
class DatabaseModule {
    @Provides
    fun provideDatabase(): Database {
        return DatabaseImpl()
    }
}

Thus, @Binds is more efficient and simpler when you just need to specify that an interface is implemented by a specific class, while @Provides is used when object creation logic is needed.

What is the difference between the Binds and Provides… - sobes.tech