【发布时间】:2018-01-22 04:24:00
【问题描述】:
我最近从 java 迁移到 kotlin,并尝试实现 dagger 2 进行依赖注入。
我已将此添加到我的 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'
这是我的模块
@Module
class AppModule(val context : Context) {
@Provides
@Singleton
fun provideContext() = context
}
这是我的组件
@Singleton
@Component(modules = arrayOf(AppModule::class))
interface AppComponent {
fun inject(application: 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)
}
}
这是我的活动
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
val context = (applicationContext as MyApplication).context
}
}
我得到这个错误
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized
这段代码在 Java 中运行,知道如何解决这个问题吗?
【问题讨论】: