如果模块范围已经是单例,是否需要使用 dagger hilt 在函数顶部添加 @Singleton?

Hay*_*yan 6 android kotlin dagger-hilt

在下面的代码中,我有一个模块,我在其中调用@InstallIn(SingletonComponent::class). singleton因此,该模块的范围是应用程序范围或单例范围))如果我将在模块内提供某些内容,我是否还需要注释该函数?

在此输入图像描述

Yun*_*s D 11

是的,您还必须用单例注释该函数。

@InstallIn(SingletonComponent::class) 意味着您可以在@Provides函数中使用单例,没有它,您无法使@Provides函数成为单例。在 hilt 中,@Provides函数默认没有作用域,因此如果您不使用单例注释@Provides函数,则每次它都会返回新对象。

您可以使用下面的代码轻松测试我的答案

var count = 0

class TestingClass() {
    init {
        count++
    }

    fun printCount() = println("count: $count")
}

@Module
@InstallIn(SingletonComponent::class)
class TestModule {

    @Provides
    @Singleton // without this count will increase every time you inject TestingClass
    fun provideTestClass(): TestingClass {
        return TestingClass()
    }
}
Run Code Online (Sandbox Code Playgroud)