I'm learning Dagger2 and I'm trying to build a very dumb example (Mainactivity have to instantiate a Car class).
And I have to handle with this error .Application does not implement dagger.android.HasAndroidInjector
if I've understood correctly :
- my component need to be annotated @Component and have to reference my module @Module ( with some methodes annotated @Provides)
- I have to use the lateinit var to instantiate my class and use the annotation @Inject.
Where I failed?
My MainActivity:
class MainActivity : DaggerAppCompatActivity() {
@Inject
lateinit var car: Car
public var brand: String = "Peugeot"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
DaggerAppComponent.builder().application(application).buildAppComponent()
car.name = brand
Log.e("CarText", "onCreate: ${car.name}")
}
My AppComponent
@Component(
modules = arrayOf(AppModule::class)
)
public interface AppComponent : AndroidInjector<AppComponent>{
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): Builder
fun buildAppComponent(): AppComponent
}
My AppModule
@Module
class AppModule {
companion object{
@Provides
fun createCar(): Car {
return Car("")
}
}
}
and to finish my car class
data class Car(var name: String)