Leandro Borges Ferreira
Leandro Borges Ferreira

Reputation: 12782

Dagger 2 - Inject with default value in constructor

How I can inject this constructor:

class SomeClass @Inject constructor(
        dep: Dependency,
        context: Context,
        private val otherClass: OtherClass = OtherClass()
)

I am only providing Dependency and Context... But it says that it cannot provide OtherClass. It should need this class, since it has a default value... How can I make this work?

Upvotes: 10

Views: 5175

Answers (2)

Damien LeBerrigaud
Damien LeBerrigaud

Reputation: 51

Since Dagger is implemented in Java, it cannot use the default value of your constructor when generating code. If you still want to leverage that default value, your only option is to create an @Provides annotated function for SomeClass in one of your Dagger modules.

@Provides
fun provideSomeClass(dep: Dependency, context: Context): SomeClass =
    SomeClass(dep, context)

Upvotes: 2

Lukas
Lukas

Reputation: 1215

I think the easiest way is to inject OtherClass as well:

class OtherClass @Inject constructor()

you can also play with @Named annotation in order to distinct from default implementation and custom OtherClass(but I think you should put both injections in module to avoid confusion):

//edit: see following example

public static class Pojo {
    final String string;

    Pojo(String string) {
        this.string = string;
    }

    @Override
    public String toString() {
        return string;
    }
}

@Provides
@Named("custom")
String provideCustomString() {
    return "custom";
}

@Provides
String provideDefaultString() {
    return "default";
}

@Provides
@Named("custom")
Pojo providesCustomPojo(@Named("custom") String custom) {
    return new Pojo(custom);
}

@Provides
Pojo providesDefaultPojo(String defaultString) {
    return new Pojo(defaultString);
}

in order to inject custom put @Inject @Named("custom") annotations (sorry for java)

Upvotes: 1

Related Questions