在Kotlin中設(shè)置Dagger有一些不同,但大多數(shù)都非常簡單,其中也有不少坑。
1.按照正常步驟創(chuàng)建kotlin項目,(要打開全部設(shè)置需要在下圖中點config,打開界面選中 全部使用kotlin)

config.png
2.在 build.gradle中添加相關(guān)配置
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
kapt 'com.google.dagger:dagger-compiler:2.5'
3.按照Dagger的傳統(tǒng)三步
3.1創(chuàng)建module
@Module
class AppModule(val app: App) {
@Provides @Singleton fun provideApp() = app
}
3.2實現(xiàn)Component
@Singleton
@Component(modules = arrayOf(AppModule::class))
interface ApiComonent {
fun inject(app: App)
}
3.3 創(chuàng)建app
class App : Application() {
init {
instance = this
}
@Inject lateinit var apiComponent: ApiComonent
override fun onCreate() {
super.onCreate()
DaggerApiComonent.builder().appModule(AppModule(this)).build().
inject(this)
}
companion object {
lateinit var instance: App
}
}
如果遇到Circular dependency between the following tasks:這個錯誤,需要進(jìn)行降級處理,修改項目根目錄里面的build.gradle,
buildscript {
//此處降級 Circular dependency between the following tasks:
ext.kotlin_version = '1.1.2-2'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}