Created
July 29, 2025 11:13
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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