My current Android project employs a number of Kotlin data classes that employ builders to construct them.
I wish to inject an instance into the Kotlin data class.
Each of my data classes have this basic structure
data class MyDataKlass( val onError: Consumer<in Throwable>,
val onComplete: Action,
val dbController: DatabaseController,
val lnController: ILoginNetworkController) : BaseSO() {
@SuppressLint("CheckResult")
fun execute() {
}
}
fun myFunction(block: MyDataKlassBuilder.() -> Unit): MyDataKlass = MyDataKlassBuilder().apply(block).build()
class MyDataKlassBuilder {
var onError: Consumer<in Throwable> = Consumer { }
var onComplete: Action = Action { }
lateinit var dbController: DatabaseController
lateinit var lnController: ILoginNetworkController
fun build(): MyDataKlass = MyDataKlass(onError, onComplete, dbController, lnController)
}
I employ these classes as follows:-
val myFunction = myFunction {
onComplete = Action { syncWorkerResult = Result.success() }
dbController = databaseController
lnController = loginNetwork
onError = Consumer {
syncWorkerResult = Result.failure()
}
}
myFunction.execute()
Currently I am passing in my database ( DatabaseController
) and network( ILoginNetworkController
) controllers into the Builders of the Kotlin Data classes
I wish to @Inject them to make my code "cleaner"
I can @Inject both into my Activities and Repositories but cannot see how to employ Dagger to inject them into the above Data Classes.
Is it possible to @Inject into Kotlin Data Classes?
I never tried this syntax on a data class, but it may be the good one:
data class MyDataKlass @Inject constructor(
val onError: Consumer<in Throwable>,
val onComplete: Action,
val dbController: DatabaseController,
val lnController: ILoginNetworkController
) : BaseSO() {
@SuppressLint("CheckResult")
fun execute() {
}
}
and in your activity:
lateinit var dataKlass: MyDataKlass @Inject set
Of course, your dependency graph will have to specify how to provide all the parameters of the data class.
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.