Discover how Hilt can save you from tangled code and endless bugs by managing your app's dependencies effortlessly!
Why Dependency injection with Hilt in depth in Android Kotlin? - Purpose & Use Cases
Imagine building an Android app where every screen needs to create and manage its own objects like database helpers, network clients, or user settings managers.
You write code to create these objects manually in each screen or class.
This manual approach quickly becomes messy and hard to maintain.
Every time you want to change how an object is created, you must update many places.
It's easy to make mistakes like creating multiple copies of the same object or forgetting to clean up resources.
Hilt automatically provides the objects your app needs, managing their creation and lifecycle for you.
You just declare what you need, and Hilt injects it where required.
This keeps your code clean, easy to test, and scalable.
val dbHelper = DatabaseHelper(context) val networkClient = NetworkClient() val userManager = UserManager(dbHelper, networkClient)
@Inject lateinit var userManager: UserManager // Hilt provides UserManager automatically
It enables building modular, testable, and maintainable Android apps by cleanly managing dependencies across the app.
In a shopping app, Hilt can provide a single instance of a cart manager to all screens, ensuring the cart data stays consistent without manual wiring.
Manual object creation leads to duplicated, hard-to-maintain code.
Hilt automates dependency management, improving code clarity and reliability.
Using Hilt makes your app easier to test and scale.
Practice
@Module and @Provides annotations in Hilt?Solution
Step 1: Understand the role of @Module
@Module is used to group methods that provide dependencies to Hilt.Step 2: Understand the role of @Provides
@Provides annotates methods inside a module to tell Hilt how to create specific dependencies.Final Answer:
To tell Hilt how to create and supply dependencies -> Option AQuick Check:
@Module + @Provides = supply dependencies [OK]
- Confusing @Module with @AndroidEntryPoint
- Thinking @Provides creates UI elements
- Assuming @Module is for navigation
Solution
Step 1: Identify how to enable injection in Activity
Hilt requires the Activity to be annotated with @AndroidEntryPoint to generate necessary code.Step 2: Inject dependencies with @Inject
Fields or constructor parameters annotated with @Inject receive dependencies automatically.Final Answer:
Annotate the Activity with @AndroidEntryPoint and use @Inject on the field -> Option AQuick Check:
@AndroidEntryPoint + @Inject field = inject Activity dependency [OK]
- Trying to use @Module on Activity
- Calling non-existent Hilt.inject() method
- Adding @Provides on constructors
MyViewModel is injected?class MyRepository @Inject constructor() {
fun getData() = "Data from repository"
}
@HiltViewModel
class MyViewModel @Inject constructor(private val repo: MyRepository) : ViewModel() {
fun fetch() = repo.getData()
}Solution
Step 1: Understand constructor injection in MyRepository
MyRepository has an @Inject constructor, so Hilt can create it automatically.Step 2: MyViewModel receives MyRepository via constructor injection
Hilt injects MyRepository instance into MyViewModel, so calling fetch() returns repo.getData() string.Final Answer:
"Data from repository" -> Option DQuick Check:
Constructor injection returns data string [OK]
- Assuming @Provides is always needed
- Expecting runtime null errors with constructor injection
- Confusing method names in ViewModel
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
fun provideHttpClient(): OkHttpClient {
return OkHttpClient()
}
@Provides
fun provideRetrofit(client: OkHttpClient): Retrofit {
return Retrofit.Builder()
.client(client)
.baseUrl("https://api.example.com")
.build()
}
}Solution
Step 1: Review Retrofit.Builder usage
Retrofit requires a converter factory (like GsonConverterFactory) to parse responses; missing here causes runtime error.Step 2: Check other options for correctness
@Singleton is optional but recommended; object is valid for modules; OkHttpClient can be created without parameters.Final Answer:
Retrofit.Builder() requires a converter factory -> Option BQuick Check:
Retrofit needs converter factory to build properly [OK]
- Thinking @Singleton is mandatory for all providers
- Confusing object vs class for modules
- Assuming OkHttpClient needs parameters
Logger using Hilt. How can you distinguish them during injection?Solution
Step 1: Understand multiple implementations injection
When multiple bindings exist for the same type, Hilt requires qualifiers to distinguish them.Step 2: Use @Named qualifiers
Annotate provider methods and injection points with @Named("name") to specify which implementation to inject.Final Answer:
Use @Named qualifiers with different names on provider methods and injection points -> Option CQuick Check:
Multiple implementations need @Named qualifiers [OK]
- Assuming module separation alone distinguishes implementations
- Using @Singleton to differentiate implementations
- Expecting automatic list injection without setup
Ready to prove it?
Pass the test and this pattern moves unknown
