Issue
I have a data class of Worker,
data class Worker(val id: Int, val name:String, val gender :String, val age :Int, val tel:String,val email:String)
and a list of workers
List<Worker> = listOf(workerA, workerB)
I want to write a function to update the data of Worker, e.g.:
updateWorkerData(1, age, 28)
//'type' refer to name, gender, age ..
//'value' refer AA, Female, 27 ..
fun updateWorkerData(id: Int, type: Any, value: Any) {
val workers = getListOfWorker()
workers.forEach {
if (it.id == id) {
//here is where I stuck
}
}
}
I'm stuck on how to refer the type to the value in Data class Worker. Need some guide on how to update the Worker's data. Thanks.
Solution
Your data class should have mutable properties, so that they can be changed:
data class Worker(val id: Int, var name: String, var gender: String, var age: Int, var tel: String, var email: String)
Then you can pass out the KProperty to the function that can change that propety:
fun <T> updateWorkerData(id: Int, property: KMutableProperty1<Worker, T>, value: T) {
val workers = getListOfWorker()
workers.forEach {
if (it.id == id) {
property.set(it, value)
}
}
}
updateWorkerData(1, Worker::age, 28)
Answered By - Animesh Sahu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.