Middle
Miks peaks kasutama @Binds annotatsiooni @Provides asemel?
sobes.tech AI
Vastus AI-lt
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 module instance. - Readability: The code becomes clearer as it explicitly shows which class implements which interface.
- Reducing boilerplate code: When using
@Binds, there's no need to write an additional@Providesmethod that just returns an implementation instance.
Example:
Instead of:
@Module
class MyModule {
@Provides
fun provideMyInterface(implementation: MyInterfaceImpl): MyInterface {
return implementation;
}
}
interface MyInterface {
// ...
}
class MyInterfaceImpl : MyInterface {
// ...
}
It's better to use:
@Module
abstract class MyModule { // Module must be abstract
@Binds
abstract fun bindMyInterface(implementation: MyInterfaceImpl): MyInterface; // Method must be abstract
}
interface MyInterface {
// ...
}
class MyInterfaceImpl : MyInterface {
// ...
}
The @Provides annotation remains necessary for providing objects that are not interface implementations or require more complex instantiation logic (e.g., creating objects via builders, providing objects from third-party libraries, providing dependencies that cannot be injected via constructor).