Currently, Hilt modules treat the absence of a scope annotation on a @Provides or @Binds method as an implicit directive to make the dependency unscoped. While this reduces boilerplate for simple data types, it frequently leads to hidden performance regressions, object-allocation overhead, and state bugs when developers accidentally omit a scope annotation (like @Singleton) on heavy infrastructure objects (e.g., Retrofit instances, Room databases).
I would like to propose an optional, strict compiler configuration flag (e.g., an annotation processor option or a compiler argument) that forces all Hilt modules to declare an explicit scope strategy.
Proposed Solution
- Introduction of an
@Unscoped annotation: A built-in Hilt annotation used to explicitly declare that a dependency is intentionally transient and should not be cached by its component.
- Strict Compiler Mode: When enabled via Gradle arguments, the Hilt compiler should throw a build-time compilation error if a
@Provides or @Binds method is missing both a standard lifecycle scope (like @Singleton, @ActivityScoped) and the explicit @Unscoped annotation.
Example Code
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideRetrofit(): Retrofit = ... // Allowed
@Provides
@Unscoped
fun provideDateFormatter(): DateFormatter = ... // Allowed
@Provides
fun provideHeavyClient(): HeavyClient = ... // Will fail compilation under strict mode
}
Benefits to the Android Ecosystem
- Fail-Fast Error Prevention: Catches accidental pasting or omission errors immediately at compile time rather than relying on manual code reviews or catching runtime performance degradation.
- Architectural Clarity: Forces self-documenting code where the memory allocation intent of every single dependency binding is completely transparent to anyone reviewing the repository.
Currently, Hilt modules treat the absence of a scope annotation on a
@Providesor@Bindsmethod as an implicit directive to make the dependency unscoped. While this reduces boilerplate for simple data types, it frequently leads to hidden performance regressions, object-allocation overhead, and state bugs when developers accidentally omit a scope annotation (like@Singleton) on heavy infrastructure objects (e.g., Retrofit instances, Room databases).I would like to propose an optional, strict compiler configuration flag (e.g., an annotation processor option or a compiler argument) that forces all Hilt modules to declare an explicit scope strategy.
Proposed Solution
@Unscopedannotation: A built-in Hilt annotation used to explicitly declare that a dependency is intentionally transient and should not be cached by its component.@Providesor@Bindsmethod is missing both a standard lifecycle scope (like@Singleton,@ActivityScoped) and the explicit@Unscopedannotation.Example Code
Benefits to the Android Ecosystem