简体   繁体   中英

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?

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.

It is not a problem with Dagger. The error clearly states that you have declared a property with a lateinit but have not initialized it in Kotlin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM