Dependency injection with Hilt

Part 2 ( Field injection )

Step 1. Inject dependencies into Android classes

Add @AndroidEntryPoint whenever you want to inject fields

Note: If you annotate an Android class with @AndroidEntryPoint, then you also must annotate Android classes that depend on it. For example, if you annotate a fragment, then you must also annotate any activities where you use that fragment.

// ToDo 1: Add @AndroidEntryPoint To inject fields in Fragment
class FirstFragment : Fragment() {

Step 2. use the @Inject annotation to perform field injection

// ToDo 3: To inject a new instance of Car
// use the @Inject annotation to perform field injection

Now we need to tell Hilt, How to create an instance for this field?

Step 3. Use the @Inject annotation on the constructor of a class

//ToDo 4 : Tell Hilt how to create instance by add @Inject annotation before constructor

class Car @Inject constructor(private val engine: Engine) {

Congratulations now you learn how to inject fields using Hilt

Get the code

Get the code from GitHub: (Link)

$ git clone

Up Next: Part 3 / Part 1