androidkotlindependency-injectiondagger-hilt

why should we not use "@Inject constructor" in the module class?


I have never seen inject constructor in the module class while using Hilt. I tried to use and did not get any error. When we inject the retrofit, we use the object class. But we can use normal class and inject constructor keywords for creating object of module class. I mean like below code. Why should we not code like below ?

@Module
@InstallIn(SingletonComponent::class)
class NetworkModule @Inject constructor () {

    @Provides
    fun provideRetrofit(): Retrofit {
        return Retrofit.Builder()
            .baseUrl("https://example.com")
            .build()
    }
}

Solution

  • Because it doesn't make sense. It doesn't throw an error and works fine, but there's no reason to do it this way.

    1. One of the purposes of @Inject is to tell Hilt that the class can be injected somewhere, making it a dependency. It doesn't make sense to use it with a @Module class, because in most cases, you won't inject a Hilt module class anywhere in your code (I really don't see any case you would).

    2. You also won't inject anything into a module class, because it is a class only Hilt uses and it already has all the information it needs in the @Module and @InstallIn annotation.

    3. That being said, doing this only lead to confusion for those who sees the code, wondering where the module class will be injected into your project.

    As already said, only Hilt will use this class and it only needs one instance of it, that's why it is better being an object, representing a single static instance.