Dagger 2 - 在构造函数中注入默认值

Lea*_*ira 5 android kotlin dagger-2

我如何注入这个构造函数:

class SomeClass @Inject constructor(
        dep: Dependency,
        context: Context,
        private val otherClass: OtherClass = OtherClass()
)
Run Code Online (Sandbox Code Playgroud)

我只提供 Dependency 和Context... 但它说它不能提供OtherClass. 它应该需要这个类,因为它有一个默认值......我怎样才能使它工作?

Luk*_*kas 1

我认为最简单的方法也是注入OtherClass

class OtherClass @Inject constructor()

您还可以使用@Named注释来区别默认实现和自定义OtherClass(但我认为您应该将这两个注入都放在模块中以避免混淆):

//编辑:参见下面的示例

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);
}
Run Code Online (Sandbox Code Playgroud)

为了注入自定义放置@Inject @Named("custom")注释(对不起java)