Reputation: 10661
I was going through one of my colleagues codebase. And I found this piece of code.
@Module
object SampleAppModule {
@Provides
@JvmStatic
@AppScope
fun provideAppDependency(context: Context): AppDependency = SampleAppDependency(context)
}
And this got me thinking, how's this different from this
@Module
class SampleAppModule {
@Provides
@AppScope
fun provideAppDependency(context: Context): AppDependency = SampleAppDependency(context)
}
I've seen the use of object in dagger modules recently, but I myself never used it because I didn't understand what it does. Would love to get some insights.
p.s. I tried changing the object to class, and it worked. Now I really don't know if there is any difference.
Upvotes: 2
Views: 1106
Reputation: 20734
Using object
to declare your Dagger modules would create only a single instance of it.
If your modules with @Provides
are declared as class
instead of object
, then an additional object is generated on building the component. So using object
, you get better performance.
Another way to do this would be using companion object
. But that is not recommended:
Beyond that, don't use
companion object
for modules. Useobject
. In that case the instance will be unused and its initialization code will be removed by R8 and the methods will be truly static and can also be inlined just like Java.
Upvotes: 4