Level 10
Dependency Injection (Hilt)
Hilt for DI
Automating how classes get their dependencies.
📚 Explanation
Hilt (built on Dagger) automates dependency injection. `@Module` defines how to create dependencies. `@InstallIn` specifies the component scope. `@HiltAndroidApp` initializes Hilt in the Application class. `@AndroidEntryPoint` enables field injection in Activities/Fragments.
Note: Code execution is not available for Android/Kotlin in the browser. Use Android Studio to run and test the app.
@Module@InstallIn(SingletonComponent::class) // Available throughout the appobject NetworkModule {@Provides@Singletonfun provideRetrofit(): Retrofit {return Retrofit.Builder().baseUrl("https://api.example.com/").build()}@Providesfun provideUserService(retrofit: Retrofit): UserService {return retrofit.create(UserService::class.java)}}// Application setup@HiltAndroidAppclass MyApp : Application()// Activity Setup@AndroidEntryPointclass MainActivity : ComponentActivity() { ... }