Search code examples
androidkotlindagger

Kotlin Dagger not inject


I recently move from java to kotlin, and try to implement dagger 2 for dependency injection.

I've add this to my gradle

apply plugin: 'kotlin-kapt'

implementation "com.google.dagger:dagger:2.11"
kapt "com.google.dagger:dagger-compiler:2.11"
compileOnly 'javax.annotation:jsr250-api:1.0'

Here is my module

@Module
class AppModule(val context : Context) {
    @Provides
    @Singleton
    fun provideContext() = context
}

Here is my component

@Singleton
@Component(modules = arrayOf(AppModule::class))
interface AppComponent {
    fun inject(application: Application)
}

Here is my Application

class MyApplication : Application() {
    @Inject
    lateinit var context : Context

    lateinit var appComponent : AppComponent

    override fun onCreate() {
        super.onCreate()

        appComponent = DaggerAppComponent.builder()
                .appModule(AppModule(this.applicationContext))
                .build()
        appComponent.inject(this)
    }
}

Here is my activity

class SplashActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        val context = (applicationContext as MyApplication).context
    }
}

and i get this error

Caused by: kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized

This code is working in Java, any idea how to solve this?


Solution

  • The context property is declared in the MyApplication class, but you're injecting the Application base class here:

    fun inject(application: Application)
    

    ... which has no injectable properties. You have to make an inject method in your component for the specific class instead:

    fun inject(application: MyApplication)
    

    Here's an answer explaining how you can use Dagger with hierarchies in more detail.