Kotlin - dagger 2
Dependencies Project build.gradle buildscript { ext.dagger_version = '2.5' } App build.gradle apply plugin: 'kotlin-kapt' dependencies { implementation "com.google.dagger:dagger:$dagger_version" kapt "com.google.dagger:dagger-compiler:$dagger_version" } 下面我們直接來看一個範例: 我這邊使用四個Model,分別為Model A B C D ModelA 裡面包含了 B跟C ModelC 裡面包含了 D 先看ModelA: class ModelA @Inject constructor(val context: Context, var modelB: ModelB, var modelC: ModelC){ var somethingData: String = "modelA haha " fun print() { Log.d("ModelA", somethingData + modelB.somethingData + modelC.somethingData) } } 傳入的context,實際上沒用到只是純粹練習 print() 會印出ModelA的data,data會將ABC的data加起來 ModelB: class ModelB @Inject constructor(){ var somethingData: String = "modelB haha " } ModelC: class ModelC @Inject constructor(modelD: ModelD){ var somethingData: String = "modelC haha " + modelD.somethingData