1

In Kotlin, you can inject a field member like this:

@Inject lateinit var coffee: Coffee

But I have noticed after playing around with Dagger that while this works, coffee will always be null unless a module and component is used and then a component builder is used to create the Coffee dependency. Is that true? Is it not possible to just have a module without having to also have a component?

Johann
  • 27,536
  • 39
  • 165
  • 279

2 Answers2

1

@Inject annotations and modules are used to let Dagger know how to create dependencies. Dagger then needs something that can actually create things with those dependencies. This is where the components come in, and this is why you declare the interface methods that return the types where you want to inject stuff in them.

Dagger will use the components' methods to generate the dependency injected implementations. People usually say that components act as the "glue" between dependencies, as components set the roots of the object graphs through their methods.

So, answering your question: yes, you need at least one component.

Ricardo Costeira
  • 3,171
  • 2
  • 23
  • 23
1

Asking to inject based on a Module without a Component is a bit like asking if you can have dinner if you have a recipe but no kitchen. The Module is just the recipe (configuration); the Component does all the cooking (creation). In this analogy, the implementations themselves would be the ingredients, which Dagger prepares on demand for you.

Most of Dagger's functionality comes from the implementation Dagger makes based on the interface you annotate with @Component. The rest of Dagger's codegen processes your @Module classes and your classes that use @Inject so that Dagger can call methods and constructors and set fields, but without a @Component nothing will call those helper classes. So in all cases a @Component is really necessary.

That said, as long as you have a Component, you do have a choice whether to let Dagger create your class—retrieving the instance from Dagger—or to create your class manually and let Dagger populate its @Inject members later.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251