-2

I'm learning dependency injection, the following Code A is from https://developer.android.com/codelabs/android-hilt#6

It seems that Code B can also work well.

What are there different when I replace object DatabaseModule with class DatabaseModule?

Code A

@Module
object DatabaseModule {

    @Provides
    @Singleton
    fun provideDatabase(@ApplicationContext appContext: Context): AppDatabase {
        return Room.databaseBuilder(
            appContext,
            AppDatabase::class.java,
            "logging.db"
        ).build()
    }

    @Provides
    fun provideLogDao(database: AppDatabase): LogDao {
        return database.logDao()
    }
}

Code B

@InstallIn(SingletonComponent::class)
@Module
class DatabaseModule {
    @Provides
    @Singleton
    fun provideDatabase(@ApplicationContext appContext: Context): AppDatabase {
        return Room.databaseBuilder(
            appContext,
            AppDatabase::class.java,
            "logging.db"
        ).build()
    }

    @Provides
    fun provideLogDao(database: AppDatabase): LogDao {
        return database.logDao()
    }
}
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

1

With the provided link, you answered your own answer. As it says:

In Kotlin, modules that only contain @Provides functions can be object classes. This way, providers get optimized and almost in-lined in generated code.

So yes, you are right, both modules work, but an object Module is automatically optimized. Don't forget, that a Kotlin Object is a static class and therefore there can never be two instances of it (maybe easier for the dagger compiler?)

Andrew
  • 4,264
  • 1
  • 21
  • 65