我第一次开始使用Kotlin和Dagger 2。我假设一切都与Java相同,但显然,并不完全。 Dagger不会为我生成Dagger *文件。这是我的代码:
组件:
@PerActivity
@Subcomponent(modules = arrayOf(ApplicationModule::class))
interface ActivityComponent {
fun inject(app: OneAccountApplication)
}
@Singleton
@Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent {
fun inject(syncService: SyncService)
@ApplicationContext fun context(): Context
fun application(): Application
fun ribotsService(): OneAccountService
fun preferencesHelper(): PreferencesHelper
fun databaseHelper(): DatabaseHelper
fun dataManager(): DataManager
}
@ConfigPersistent
@Component(dependencies = arrayOf(ApplicationComponent::class))
interface ConfigPersistentComponent {
fun activityComponent(activityModule: ActivityModule): ActivityComponent
}
模块:
@Module
class ActivityModule(private val mActivity: Activity) {
@Provides
internal fun provideActivity() = mActivity
@Provides
@ActivityContext
internal fun providesContext() = mActivity
}
@Module
class ApplicationModule(val mApplication: Application) {
@Provides @Singleton
internal fun provideApplication() = mApplication
@Provides
@ApplicationContext
internal fun provideContext() = mApplication
@Provides
@Singleton
internal fun provideOneAccountService() = OneAccountService.Creator.newOneAccountService()
}
范围注释:
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityContext
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ApplicationContext
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ConfigPersistent
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class PerActivity
这基本上是我在我的java代码中成功使用的整个DI系统。但是对于Kotlin来说,由于某种原因它不起作用。我还添加了apply plugin: 'kotlin-kapt'
到gradle.build
,如:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
在依赖关系中,我有:
dependencies {
final DAGGER_VERSION = '2.8'
def daggerCompiler = "com.google.dagger:dagger-compiler:$DAGGER_VERSION"
annotationProcessor daggerCompiler
testAnnotationProcessor daggerCompiler
androidTestAnnotationProcessor daggerCompiler
compile "com.google.dagger:dagger:$DAGGER_VERSION"
}
kapt {
generateStubs = true
}
基本上,它https://github.com/ribot/android-boilerplate转变为Kotlin。
答案 0 :(得分:3)
Kotlin使用kapt
代替Android插件中的annotationProcessor
。
您需要在build.gradle
文件中包含并使用以下内容:
kapt {
generateStubs = true
}
dependencies {
// ...
kapt daggerCompiler
}
此处还可以找到更详细的说明:Dagger and Kotlin