我正在浏览我的一位同事的代码库。我找到了这段代码。
@Module
object SampleAppModule {
@Provides
@JvmStatic
@AppScope
fun provideAppDependency(context: Context): AppDependency = SampleAppDependency(context)
}
这让我思考,这与这个有何不同
@Module
class SampleAppModule {
@Provides
@AppScope
fun provideAppDependency(context: Context): AppDependency = SampleAppDependency(context)
}
我最近在 dagger 模块中看到了 object 的使用,但我自己从未使用过它,因为我不明白它的作用。很想获得一些见解。
附:我尝试将对象更改为类,并且成功了。现在我真的不知道有什么区别。
最佳答案
使用 object
声明 Dagger 模块只会创建它的一个实例。
如果带有 @Provides
的模块被声明为 class
而不是 object
,那么在构建组件时会生成一个附加对象。因此,使用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.
关于android - 在 dagger 模块的上下文中,Kotlin 对象和类有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63085043/