You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hilt报错kotlin.UninitializedPropertyAccessException:未初始化lateinit属性解决方法

解决Hilt中lateinit属性未初始化的问题

问题出在@HiltViewModel的依赖注入方式上:Hilt不会自动初始化ViewModel类内部的字段注入(@Inject lateinit var),ViewModel的依赖必须通过构造函数注入完成。

修正步骤

  1. 将CacheInterceptor移至ViewModel的构造函数参数,通过@Inject标注构造函数实现注入
  2. 移除类内部的@Inject lateinit var字段

修改后的代码

SharedDataViewModel.kt

@HiltViewModel
class SharedDataViewModel @Inject constructor(
    private val cacheInterceptor: CacheInterceptor // 构造函数注入依赖
) {
    private fun load() {
        val client = OkHttpClient().newBuilder()
            .addNetworkInterceptor(cacheInterceptor)
            .build() // 补充build()方法,原代码遗漏了这一步
    }
}

原NetWorkModule无需修改

@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()
    }
}

原因说明

Hilt对ViewModel的注入逻辑是通过自定义ViewModelProvider.Factory实现的,它仅会处理构造函数中标记的依赖注入,不会扫描并初始化类内部的@Inject字段。因此原代码中的cacheInterceptor始终未被赋值,调用时触发UninitializedPropertyAccessException。

内容的提问来源于stack exchange,提问作者Minh Tiến Đào

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 19:12:09