Saran Sankaran
Saran Sankaran

Reputation: 2606

Declare provision method of named in module dependency

My project has following setup

@Module
abstract class CoreModule {
    @Provides
    @Named("text1")
    fun textOne() = "text1"

    @Provides
    @Named("text2")
    fun textTwo() = "text2"
}

@Component(modules=[CoreModule::class])
interface CoreComponent{
    @Named("text1")
    fun textOne(): String
}

@Component(
    dependencies = [CoreComponent::class]
    modules=[AppModule::class]
)
interface AppComponent()

@Module()
class AppModule {
    fun getStringDouble(@Named("text1") text1: String) = text1 + text1
}

Here I have 2 components CoreComponent which provides dependencies to AppComponent. Now I want to provide only text1 to AppComponent.

Since I have added @Named("text1") in CoreComponent to denote which string to provide to AppComponent. It forces me to use @Named("text1") in AppModule as well, which I don't want.

How can I create provision method in CoreComponent to provide only text1 to AppComponent in such a way, that I don't have to use @Named everywhere in AppComponent

Upvotes: 4

Views: 164

Answers (2)

Anuj Jindal
Anuj Jindal

Reputation: 1719

you can remove @Named("<name>") from Provider method in CoreModule and CoreComponent.

instead, you can create a custom Qualifier annotation like this

@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
annotation class TextTwoName {
}

and do following changes

In CoreModule, use @TextTwoName in textTwo() for instead of @Named("text2") and remove @Named("text1") from fun textOne() = "text1"

In CoreComponent, remove @Named("text1") from fun textOne(): String while name function name textOne doesn't matter here only return type matters. it will take fun textOne() = "text1" from CoreModule

If you want to expose fun textTwo() = "text2" then you can add @TextTwoName annotation in the CoreComponent's fun textOne():String method.

Upvotes: 0

David Medenjak
David Medenjak

Reputation: 34552

The simplest solution would probably be to simply bind/provide it under a different key, a plain String in your example.

@Binds // bind it without any qualifier
fun plainText1(@Named("text1") text1: String) : String

If you do have multiple values for the same type then qualifiers would probably be easier to use in the long run though, since they allow you proper naming of the keys used.

Keep in mind that you can also create your own qualifiers and don't have to use @Named, it's just available by default.


An alternative to your setup altogether would be to use (Sub)components for encapsulation which would allow you to only ever return the value produced without binding the whole component dependency.

Upvotes: 3

Related Questions