Junior — Middle
Can you explain what dependency injection is and how it is used in programming?
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a design pattern where an object receives its dependencies (such as other objects or services) from outside, rather than creating them itself. This helps make the code more modular, testable, and flexible.
In programming, this is usually implemented by passing dependencies through the class constructor, setters, or interfaces. For example, in Android, DI libraries (like Dagger, Hilt) are often used to automatically create and pass the required objects.
Example in Kotlin:
class Engine {
fun start() = println("Engine started")
}
class Car(private val engine: Engine) {
fun drive() {
engine.start()
println("Car is driving")
}
}
fun main() {
val engine = Engine() // create dependency
val car = Car(engine) // inject dependency
car.drive()
}
Here, Car does not create Engine itself but receives it from outside, which simplifies replacing or testing the Engine.