Sobes.tech
Junior — Middle

Can you explain how Hilt works in the context of dependency injection?

sobes.tech AI

Answer from AI

Hilt is a dependency injection library for Android built on top of Dagger. It simplifies DI setup by automatically generating the necessary code.

The main mechanism of Hilt:

  • Annotate classes with @Inject to specify dependencies.
  • Use @Module and @Provides annotations to describe how to create objects.
  • Annotate Android components (Activity, Fragment, ViewModel) with @AndroidEntryPoint for automatic dependency injection.
  • Hilt generates components and links dependencies at compile time.

Example:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    @Inject lateinit var repository: UserRepository

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // repository is already initialized by Hilt
    }
}

@Module
@InstallIn(SingletonComponent::class)
object AppModule {
    @Provides
    fun provideUserRepository(): UserRepository {
        return UserRepositoryImpl()
    }
}

Thus, Hilt automates the creation and management of dependencies, reducing boilerplate code and errors.