Vairavan
Vairavan

Reputation: 1294

Dagger2 - How to use @Named with @BindsInstance

How is @Named used with @BindsInstance? I have the this component

interface AppComponent : AndroidInjector<MyApplication>{
    @Component.Builder
    abstract class Builder : AndroidInjector.Builder<MyApplication>() {

        @BindsInstance
        abstract fun preferenceName( @Named("PreferenceName") name : String ) : Builder
    }
}

and trying to inject in MyApplication

@Inject
@Named("PreferenceName")
lateinit var prefName : String

But it fails with MissingBinding for String. I could resolve this with a module provider but trying to avoid provider for constants.

Upvotes: 4

Views: 3375

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95704

Update: Dagger 2.25.2 has eliminated the need for workaround:

  1. Kotlin support

    ii. Qualifier annotations on fields can now be understood without The need for @field:MyQualifier (646e033)

    iii. @Module object classes no longer need @JvmStatic on the provides methods. (0da2180)


This doesn't have anything to do with @BindsInstance, but rather the @Named annotations on fields. You can tell from the "MissingBinding for String", which would otherwise give you an error about a Named string.

As in Svetlozar Kostadinov's article Correct usage of Dagger 2 @Named annotation in Kotlin, you'll need to clarify to Kotlin that you'd like the annotations to apply to the field.

@field:[Inject Named("PreferenceName")]
lateinit var prefName : String;

As Svetlozar puts it:

The reason is because in Kotlin annotations need to be slightly more complicated in order to work as expected from Java perspective. That’s coming from the fact that one Kotlin element may be a facade of multiple Java elements emitted in the bytecode. For example a Kotlin property is a facade of an underlying Java member variable, a getter and a setter. You annotate the property but what Dagger expects to be annotated is the underlying field.

Related: Dagger 2 constructor injection in kotlin with Named arguments

Upvotes: 3

Related Questions