Skip to content

Instantly share code, notes, and snippets.

@mahdiPourkazemi
Created July 29, 2025 11:13
Show Gist options
  • Save mahdiPourkazemi/4b7a0680631f10e43fe54012bda70d17 to your computer and use it in GitHub Desktop.
Save mahdiPourkazemi/4b7a0680631f10e43fe54012bda70d17 to your computer and use it in GitHub Desktop.
This snippet demonstrates a better way to inject constant values using Hilt in Android. Instead of relying on a centralized Constants.kt file and @nAmed strings (which are error-prone and hard to refactor), it uses custom @qualifier annotations. This approach provides compile-time safety, clearer dependency injection, and easier maintenance.
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class SharedPreferencesFileNameKey
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class LanguageCodeKey
@Module
@InstallIn(SingletonComponent::class)
object DataStoreKeyModule {
@Provides @SharedPreferencesFileNameKey
fun provideSharedPreferencesFileName() = "sample_shared_prefs"
@Provides @LanguageCodeKey
fun provideLanguageCodeKey() = "app_language_code"
// ... and provides for every other qualifier
}
@HiltViewModel
class MyViewModel @Inject constructor(
@LanguageCodeKey private val languageCodeKey: String,
@CurrentUserDetailsKey private val userDetailsKey: String
) : ViewModel() {
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment