匕首模块类的提供程序功能的注释 [英] The annotation for provider function of dagger module class
问题描述
我正在用Kotlin和Dagger 2开发一个Android项目.我有一个NetworkModule
,其中定义了一些提供程序功能.
I am developing an Android project with Kotlin and Dagger 2. I have a NetworkModule
in which I define some provider functions.
@Module
object NetworkModule {
@Provides
@JvmStatic // Here uses @JvmStatic
internal fun provideSomething(): Something {
...
}
}
我看到有人使用Kotlin @JvmStatic
,而有人使用dagger的@Reusable
来注释提供程序功能:
I see some people use kotlin @JvmStatic
and some use dagger's @Reusable
to annotate the provider function:
@Module
object NetworkModule {
@Provides
@Reusable // Here uses @Reusable
internal fun provideSomething(): Something {
...
}
}
和..某些人同时使用:
And..some people use both:
@Module
object NetworkModule {
@Provides
@JvmStatic // Here use both @JvmStatic
@Reusable // and uses @Reusable
internal fun provideSomething(): Something {
...
}
}
我很困惑.我的两个问题是:
I get confused. My two questions are:
-
注释
@JvmStatic
和/或@Reusable
的动机是什么?这样做的原因是什么?这样做的好处是什么?
What is the motivation to annotate either
@JvmStatic
and/or@Reusable
? What's the reason behind or what is the benefit doing so?
使用@JvmStatic
或@Reusable
哪个更好?还是一个很好?还是应该同时使用两者?如果是,那么同时使用两者的原因是什么?
Which one is better to use @JvmStatic
or @Reusable
? Or either one is fine? Or should I use both, if so what is the reason to use both then?
推荐答案
如果您将模块声明为Kotlin对象,则需要@JvmStatic
.该限制已通过 dagger 2.25 删除.您也可以选中此问题以获取更多信息.
If you declare your module as a Kotlin object, @JvmStatic
was required. That limitation was removed with dagger 2.25 You can also check this issue for more info.
如果您使用Dagger 2.25或更高版本,则不再需要使用@JvmStatic
.
If you use Dagger 2.25 or newer there is no reason to use @JvmStatic
anymore.
来自@Reusable
文档:
一个范围,该范围指示绑定返回的对象可以(但可能不会)被重用.
A scope that indicates that the object returned by a binding may be (but might not be) reused.
{@ code @Reusable}在您希望限制一种类型的配置数量时有用,但是没有特定的生存期,在该生存期中只能有一个实例.
{@code @Reusable} is useful when you want to limit the number of provisions of a type, but there is no specific lifetime over which there must be only one instance.
如果您在多个位置注入相同的对象,并且具有相同的实例不是问题,那么这可以帮助您不必为每种用法创建一个新对象.
If you inject the same thing in multiple places, and having the same instance is not a problem, this can help not to create a new object for each usage.
@JvmStatic
和@Reusable
彼此不相关,根据您的需要,您可以使用一个,另一个或两者.
@JvmStatic
and @Reusable
are not related to each other, depending on your need you can use one, the other or both of them.
这篇关于匕首模块类的提供程序功能的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!