square / anvil

A Kotlin compiler plugin to make dependency injection with Dagger 2 easier.
Apache License 2.0
1.31k stars 82 forks source link

Allow using ContributesTo to contribute provisions #728

Open gabrielittner opened 1 year ago

gabrielittner commented 1 year ago

The goal would be to allow writing this

@ContributesTo(AppScope::class)
fun provideOkHttpClient(): OkHttpClient = ...

which generates something equivalent to

@Module
@ContributesTo(AppScope::class)
object OkHttpClientModule {
  fun provideOkHttpClient(): OkHttpClient = ...
}

This would almost completely avoid the need to create module classes. Other than plain injected classes any contribution to a component would then use a @Contributes... annotation and we wouldn't need another concept like modules. The only scenario that I can think of where you'd still need a module is generic bindings but the most common case for them would be addressed by #726). The original motivation comes from this thread https://androiddev.social/@billjings@mastodon.online/110722092128294953

An implementation would need to handle scope and qualifier annotations (edit: also multibinding annotations) on the function as well as parameters to the function and their annotations.

It would also be possible to create a @ContributesProvides annotation for this but it would have the same parameters.

If this is something you'd want to support I can take a stab at implementing it.

bubenheimer commented 1 year ago

You have my vote. This approach can be extended to properties (computed and not), just as in a module: https://github.com/square/anvil/issues/578