使用 Hilt 时出现 UninitializedPropertyAccessException

UninitializedPropertyAccessException when using Hilt

我收到 lateinit 错误,但我没有看到问题

 kotlin.UninitializedPropertyAccessException: lateinit property soldatDatabase has not been initialized
        at pl.rybson.soldatlobby.di.RoomModule.provideServersDao(RoomModule.kt:37)
        at pl.rybson.soldatlobby.di.RoomModule_ProvideServersDaoFactory.provideServersDao(RoomModule_ProvideServersDaoFactory.java:27)
        at pl.rybson.soldatlobby.DaggerBaseApplication_HiltComponents_ApplicationC.getServersDao(DaggerBaseApplication_HiltComponents_ApplicationC.java:113)
        at pl.rybson.soldatlobby.DaggerBaseApplication_HiltComponents_ApplicationC.getMainRepository(DaggerBaseApplication_HiltComponents_ApplicationC.java:127)
        at pl.rybson.soldatlobby.DaggerBaseApplication_HiltComponents_ApplicationC.access00(DaggerBaseApplication_HiltComponents_ApplicationC.java:53)
        at pl.rybson.soldatlobby.DaggerBaseApplication_HiltComponents_ApplicationC$SwitchingProvider.get(DaggerBaseApplication_HiltComponents_ApplicationC.java:431)
        at pl.rybson.soldatlobby.ui.home.HomeViewModel_AssistedFactory.create(HomeViewModel_AssistedFactory.java:24)
        at pl.rybson.soldatlobby.ui.home.HomeViewModel_AssistedFactory.create(HomeViewModel_AssistedFactory.java:12)

和Module.kt

@Module
@InstallIn(ApplicationComponent::class)
object RoomModule {

    private lateinit var soldatDatabase: SoldatDatabase

    @Singleton
    @Provides
    fun provideRoom(@ApplicationContext context: Context): SoldatDatabase {
        soldatDatabase = Room.databaseBuilder(
            context,
            SoldatDatabase::class.java,
            "soldat.db"
        )
            .build()
        return soldatDatabase
    }


    @Singleton
    @Provides
    fun provideServersDao(): ServersDao {
        return soldatDatabase.serversDao()
    }

}

Dagger 仅在需要时创建依赖项。由于 provideServersDao 不接受任何参数,Dagger 得出结论,可以在没有任何依赖的情况下提供 ServersDao,并且没有理由调用 provideRoom.

因为ServersDao实际上依赖于SoldatDatabase的一个实例,你应该让Dagger为你提供一个:

@Module
@InstallIn(ApplicationComponent::class)
object RoomModule {

    @Singleton
    @Provides
    fun provideRoom(@ApplicationContext context: Context): SoldatDatabase {
        return Room.databaseBuilder(
            context,
            SoldatDatabase::class.java,
            "soldat.db"
        )
            .build()
    }


    @Singleton
    @Provides
    fun provideServersDao(soldatDatabase: SoldatDatabase): ServersDao {
        return soldatDatabase.serversDao()
    }

}