2

Can somebody explain why my code crashes when providing RoomDatabase and Dao like this:

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

    @Singleton
    @Provides
    fun provideDatabase(@ApplicationContext app: Context): RoomDatabase {
        return Room.databaseBuilder(app, AppDatabase::class.java, "db_name").build()
    }

    @Singleton
    @Provides
    fun provideMyDao(db: AppDatabase): MyDao {
        return db.myDao()
    }

}

However, providing the instance without return statement, using the = sign works perfectly fine:

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

    @Singleton
    @Provides
    fun provideDatabase(@ApplicationContext app: Context) = Room.databaseBuilder(app, AppDatabase::class.java, "db_name").build()


    @Singleton
    @Provides
    fun provideMyDao(db: AppDatabase) = db.myDao()

}

The only difference is the declaration of provider functions. Those with equal signs works. Using the declaration with curly braces and return statement gives me following error.

enter image description here

Matúš Ravas
  • 63
  • 1
  • 4

0 Answers0