问题
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 {
...
}
}
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:
What is the motivation to annotate either
@JvmStaticand/or@Reusable? What's the reason behind or what is the benefit doing so?Which one is better to use
@JvmStaticor@Reusable? Or either one is fine? Or should I use both, if so what is the reason to use both then?
回答1:
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.
If you use Dagger 2.25 or newer there is no reason to use @JvmStatic anymore.
From the @Reusable docs:
A scope that indicates that the object returned by a binding may be (but might not be) reused.
{@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 and @Reusable are not related to each other, depending on your need you can use one, the other or both of them.
来源:https://stackoverflow.com/questions/59489252/the-annotation-for-provider-function-of-dagger-module-class