Reputation: 1711
I have a custom qualifier that takes parameter -- enum value. Enum value contains information specific to the construction of the desired instance.
If I'm up to adding new value to enum it leads to same boilerplate code in the module, like this:
Qualifier(Java):
@Documented
@Qualifier
@Retention(RUNTIME)
public @interface Format {
Type value() default SYSTEM;
enum Type {
UI("dd-MM-yyyy HH:mm"),
UI_DATE("EEEE,\u00A0dd MMMM yyyy"),
.
.
.
private String format;
public String getFormat() {
return format;
}
Type(String formatString) {
format = formatString;
}
}
}
Module(Kotlin):
@Module
class DateTimeModule {
@Provides
@Format(Format.Type.UI)
fun dateTimeFormatterUI(): DateTimeFormatter {
return DateTimeFormat.forPattern(Format.Type.UI.format).withLocale(DefaultConfigVariables.LOCALE)
}
@Provides
@Format(Format.Type.UI_DATE)
fun dateFormatterUI(): DateTimeFormatter {
return DateTimeFormat.forPattern(Format.Type.UI_DATE.format).withLocale(DefaultConfigVariables.LOCALE)
}
.
.
.
}
Is it possible to change it somehow that I could only add a new instance to enum and it was passed to the provider method or something like that?
Upvotes: 0
Views: 178
Reputation: 95634
Not through Dagger alone. Unless you codegen a module that you feed into Dagger, it won't be able to programmatically read your annotations and take a varying action based on the values.
Pragmatically, though it bends the Law of Demeter, I'd do it this way:
public class DateTimeFormatterFactory {
@Inject DateTimeFormatterFactory() {}
public DateTimeFormatter forFormat(Format.Type type) {
return DateTimeFormat
.forPattern(type)
.withLocale(DefaultConfigVariables.LOCALE);
}
}
Upvotes: 1