简体   繁体   中英

Kotlin Lazy Initialisation vs Dagger Lazy injection

I have a module with a provider method for OkHttpClient as such:

@Provides
@Singleton
fun provideOkHttpClient(interceptor: HttpLoggingInterceptor): OkHttpClient {
        return OkHttpClient.Builder().addInterceptor(interceptor).build()
}

And another provider method for Retrofit as such:

@Provides
@Singleton
fun provideRetrofitBuilder(client: Lazy<OkHttpClient>,gson: Gson): Retrofit {
....
}

Now the provider for Retrofit takes in a lazily injected OkHttpClient which Dagger already knows how to create ie wrapped with Lazy from dagger package. My question is would there be a difference in behavior if it is wrapped in Lazy from dagger package which from my understanding computes its value on the first call to get() and remembers that same value for all subsequent calls to get() versus when it is wrapped in the Lazy from kotlin package which gets the lazily initialized value of the current Lazy instance? Is it even possible to use the Lazy from the kotlin package and how would this play out? Do they provide the same behavior? Thank you for your time:)

I just tried it, and the variant with kotlin.Lazy did not compile:

error: [Dagger/MissingBinding] kotlin.Lazy<? extends com.mycompany.MyClass> cannot be provided without an @Provides-annotated method.

So no, it's not possible to use Lazy from kotlin for dependency injection. At least not everywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM