Search code examples
androidkotlindagger

Field Injection using Kotlin Language is not generating DaggerComponent


I am trying to learn MVVM using Kotlin Language. I am facing some issue, kindly please help. I already searched on google, but not found any answer.

Points

  1. When I used the Constructor Injection it is working fine and generating DaggerComponent class and the object is created.
  2. When I Changed the Constructor injection to Field Injection, the DaggerComponent Class is not generating and throws some error.

Using Constructor Injection

lateinit var car: Car

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val component = DaggerCarComponent.create()
    car = component.getCar()
    car.drive()
}

Here DaggerCarComponet is generated and car object is created via dagger, and also able to call drive() method of car class.

Using Field Injector

@Inject lateinit var car: Car

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val component = DaggerCarComponent.create()
    //car = component.getCar()
    component.inject(this)
    car.drive()
}

In the above I only added the @Inject annotation on the field and then calling the inject() method of CarComponent interface. But This is not working and throwing error as soon as I added @Inject annotation on lateinit var car:Car

Here is the error

Execution failed for task ':app:kaptDebugKotlin'. A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction java.lang.reflect.InvocationTargetException (no error message)

Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Here is the build.gradle(app)

implementation 'com.google.dagger:dagger-android:2.35.1'
//implementation 'com.google.dagger:dagger-android-support:2.21' // if you use the support libraries
annotationProcessor 'com.google.dagger:dagger-android-processor:2.21'
annotationProcessor 'com.google.dagger:dagger-compiler:2.28.3'

kapt 'com.google.dagger:dagger-android-processor:2.21'
kapt 'com.google.dagger:dagger-compiler:2.28.3'

build.gradle(Project)

classpath "com.android.tools.build:gradle:7.0.4"
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.20"

Solution

  • All you need is to annotate you Car class with @AndroidEntryPoint and then try field injection.

    More info you can find here: https://developer.android.com/training/dependency-injection/hilt-android#not-supported