Whats the difference between @Inject and @Provide ?
although both are used for providing dependencies then whats the difference ?
Whats the difference between @Inject and @Provide ?
although both are used for providing dependencies then whats the difference ?
This is covered very well in documentation, @Inject and @Provides are two different ways of introducing dependencies in the dependency graph. they are suited for different use cases
@Inject@Inject on constructor or property and you are done@Provides to some people@Provides@Inject@Inject@Provides which returns Inteface typeFollowing are the examples of above three points for @Provides
// You can't mark constructor of String with @Inject but you can use @Provides
@Provides
fun provideString(): String {
return "Hello World"
}
@Provides
fun provideCar(): Car {
val car = Car()
// Do some configuration before introducing it in graph, you can't do this with @Inject
car.setMaxSpeed(100)
car.fillFuel()
return car
}
interface Logger { fun log() }
class DiscLogger : Logger{ override fun log() { } }
class MemoryLogger : Logger { override fun log() { } }
@Provides
fun provideLogger(): Logger {
val logger = DiscLogger() \\ or MemoryLogger()
return logger
}
@Inject:- It is used to inject dependencies in class. @provides:- Required to annotated the method with @provide where actual instance is created.