简体   繁体   English

Kotlin - 如何从数据类列表中更新特定值

[英]Kotlin - How to update particular value from a list of data class

I have a data class of Worker,我有一个 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, eg:我想写一个函数来更新 Worker 的数据,例如:

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.我被困在如何将类型引用到数据类 Worker 中的值。 Need some guide on how to update the Worker's data.需要一些关于如何更新 Worker 数据的指南。 Thanks.谢谢。

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:然后您可以将 KProperty 传递给可以更改该属性的函数:

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)

Animesh's answer is correct, I just wanted to point out that it may be simpler to use a Map of Workers (where the key is the worker ID), and just edit the workers directly, rather than doing clever (and difficult to understand) things with reflection: Animesh的回答是正确的,我只是想指出使用Map of Workers(其中key是worker ID)可能更简单,直接编辑workers,而不是做聪明(并且难以理解)的事情带反射:

val workers: Map<Int, Worker> = listOf(
    Worker(1, "a", "a", 1, "a", "a"),
    Worker(2, "b", "b", 2, "b", "b"),
    Worker(3, "c", "c", 3, "c", "c"),
).map { it.id to it }.toMap()

// Worker 1 changes name
workers.getValue(1).name = "Slartibartfast"

// Worker 2 gets older
workers.getValue(2).age += 1

// Worker 3 changes email
workers.getValue(3).email = "newemail@example.com"

I would prefer to use immutability instead of using mutable fields for a data class.我更喜欢使用不变性而不是对数据类使用可变字段。

A simple solution is the following:一个简单的解决方案如下:

fun List<Worker>.updateWorkerDataAge(id: Int, age: Int): List<Worker> =
        this.map { worker -> if (worker.id == id) worker.copy(age = age) else worker }

and you can use it:你可以使用它:

val newWorkerList = workerList.updateWorkerDataAge(2, 99)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM