Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 701
Leandro Borges Ferreira Avatar asked Oct 26 '17 16:10

Leandro Borges Ferreira


1 Answers

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)

like image 96
Lukas Avatar answered Oct 12 '22 11:10

Lukas