Junior — Middle
Explain the purpose and function of the @Binds annotation in the context of Dependency Injection.
sobes.tech AI
Answer from AI
The @Binds annotation is used in Dagger (Dependency Injection) to bind an interface to its implementation without the need to write factory methods.
It is applied in abstract modules and indicates that when a dependency of the interface is requested, a specific implementation should be provided.
Example:
@Module
abstract class NetworkModule {
@Binds
abstract ApiService bindApiService(ApiServiceImpl impl);
}
Here, ApiService is an interface, and ApiServiceImpl is its implementation. Dagger will automatically create a binding to provide ApiServiceImpl when ApiService is requested.
This simplifies the code, makes it more readable, and eliminates the need to write methods with @Provides if the implementation already exists.