Middle
Why should you use the @Binds annotation instead of the @Provides annotation?
sobes.tech AI
Answer from AI
The @Binds annotation is used to tell Dagger which specific implementation of an interface it should provide when the interface itself is requested.
Advantages of using @Binds instead of @Provides in this case:
- Performance:
@Bindsis more efficient because Dagger generates less code. It simply binds the interface to a specific type without creating a new instance of a module. - Readability: The code becomes more readable because it is clear which class implements which interface.
- Reducing boilerplate code: When using
@Binds, there is no need to write an additional@Providesmethod that just returns an instance of the implementation.
Example:
Instead of:
@Module
class MyModule {
@Provides
fun provideMyInterface(implementation: MyInterfaceImpl): MyInterface {
return implementation;
}
}
interface MyInterface {
// ...
}
class MyInterfaceImpl : MyInterface {
// ...
}
It is better to use:
@Module
abstract class MyModule { // The module must be abstract
@Binds
abstract fun bindMyInterface(implementation: MyInterfaceImpl): MyInterface; // The method must be abstract
}
interface MyInterface {
// ...
}
class MyInterfaceImpl : MyInterface {
// ...
}
The @Provides annotation remains necessary for providing objects that are not implementations of interfaces or require more complex instantiation logic (for example, creating objects via builders, providing objects from third-party libraries, providing dependencies that cannot be injected through the constructor).