Junior — Middle
Explain the mechanism of Dagger and its role in dependency management in an application
sobes.tech AI
Answer from AI
Dagger is a dependency injection library for Android applications. It helps manage the creation and provision of objects that other components depend on.
The main idea of Dagger is to generate code that automatically creates and links objects, eliminating the need for manual factory writing and simplifying testing.
How it works:
- You declare modules (@Module) that provide dependencies through methods annotated with @Provides.
- Components (@Component) connect modules and dependency injection points.
- Dagger generates code that creates objects and injects them where needed (@Inject).
Example:
class Engine @Inject constructor() {
fun start() = println("Engine started")
}
class Car @Inject constructor(private val engine: Engine) {
fun drive() {
engine.start()
println("Car is driving")
}
}
@Component
interface CarComponent {
fun getCar(): Car
}
// Usage
val carComponent = DaggerCarComponent.create()
val car = carComponent.getCar()
car.drive()
Thus, Dagger simplifies dependency management, improves modularity, and makes code maintenance easier.