Let's say I want to create an object that follows the Singleton pattern. I can do it in the following ways:
Method 1: Singleton using Lazy Initialization
@Singleton
object RetrofitCreator {
val retrofitBuilder: Retrofit.Builder by lazy {
Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create())
.baseUrl("https://sample.com")
.build()
.create(ApiService::class.java)
}
}
Method 2: Singleton with Hilt Annotations
@Module
@InstallIn(ApplicationComponent::class)
object RetrofitCreator {
@Provides
fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://sample.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
What is the difference between the two methods I have shown? Is one of them better than the other? If so, which method and why?