androidkotlindagger-hilt

Hilt: kotlin.UninitializedPropertyAccessException: lateinit property has not been initialized


I using Hilt, but it raised an error: kotlin.UninitializedPropertyAccessException: lateinit property cacheInterceptor has not been initialized. How do I fix it?

@Module
@InstallIn(SingletonComponent::class)
object NetWorkModule {
    @Singleton
    @Provides
    fun provideCacheInterceptor(): CacheInterceptor {
        return CacheInterceptor()
    }
}

class CacheInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val response: Response = chain.proceed(chain.request())
        val cacheControl = CacheControl.Builder()
            .maxAge(1, TimeUnit.DAYS)
            .build()
        return response.newBuilder()
            .header("Cache-Control", cacheControl.toString())
            .build()
    }
}

@HiltViewModel
class SharedDataViewModel @Inject constructor(
) {
 @Inject lateinit var cacheInterceptor: CacheInterceptor


 private fun load() {
     val client = OkHttpClient().newBuilder()
    .addNetworkInterceptor(cacheInterceptor) //kotlin.UninitializedPropertyAccessException: //lateinit property cacheInterceptor has not been initialized
 }

}

Solution

  • Just inject in the constructor and it'll work.

    like this in ViewModel:

    @HiltViewModel
    class SharedDataViewModel @Inject constructor(
     var cacheInterceptor: CacheInterceptor
    ) {
    

    In fragment, you can inject like this:

     @Inject lateinit var cacheInterceptor: CacheInterceptor